WebAPI下的如何实现参数绑定

  本文将概述在WebAPI方式下将如何将参数绑定到一个action方法,包括参数是如何被读取,一系列规则决定特定环境采用的那种绑定方式,文章最后将给出一些实际的例子。

  Parameter binding说到底是接到一个Http请求,将其转换成.NET类型使得action方法的签名更易于理解。托福答案

  请求消息(request message)包括了请求的所有信息,如带查询字符串的请求地址(URL),内容主体(content body)及头部信息(header)。在没有采用parameter binding

  的情况下,每个action方法将需要接收request message,并手动从中提取出参数,如下所示:

  public object MyAction(HttpRequestMessage request){ // make explicit calls to get parameters from the request object int id = int.Parse(request.RequestUri.ParseQueryString().Get("id")); // need error logic! Customer c = request.Content.ReadAsAsync().Result; // should be async! // Now use id and customer}

  很显然,这样的方式丑陋,易出错,代码重复,而且难以单元测试。我们希望action的签名类似以下的形式:

  public object MyAction(int id, Customer c) { }

  那么WebAPI是如何将request message转换成像id和customer这样的参数的呢?托福答案

  Model Binding vs. Formatters

  参数绑定有两种技术:Model Binding和Formatters。实际上,WebAPI使用model binding读取查询字符串(query string)内容进行参数绑定,使用Formatters读取主体内容

  (body content)进行参数的绑定。

  Using Model Binding:

  ModelBinding和MVC中的此概念是一致的,更多内容见Here。通常有一个"ValuePeoviders"提供数据片断如查询字符串参数,model binder将这些片断组合成一个对象。

  Using Formatters:

  Formatters(如MediaTypeFormatter类所示)实际上是包含额外元数据的序列化程序。WebAPI从HttpConfiguration中获取一个formatters的列表,然后通过request信息

  中的content-type来判断采用具体合适的formatter。WebAPI有不少默认的formatters。默认的JSON formatter是JSON.NET。还有Xml formatter和采用JQuery语法的

  FormUrl formatter。

  其中Formatters的核心方法是MediaTypeFormatter.ReadFromStreamAsync,如下所示:

  public virtual Task
 

posted on 2013-10-10 11:27  haosola  阅读(232)  评论(0编辑  收藏  举报

toeflacttoeflieltstoefltoeflact