可同时参见这篇文章 Jquery下Json数据的传递与解析(asp.net mvc与asp.net api下后台json接收方式的不同)

早先使用webapi ,希望通过使用jquery下的ajax方式post json格式数据到后台并接收处理返回json数据。但发现后台无法像之前在mvc下形如以下这种方式:

public IList<Site> SiteList(int startId, int itemcount)

接收前台传来的json数据。后尝试后台定义一个与前台传递的json数据类型对应的类发现能接收前台json数据,一直不明原因。

后发现以下这篇文章有同样的疑问。

ASP.NET WebAPI RC 竟然不支持最常用的json传参

文章本身没指出具体原因所在,下面评论的朋友给出了启示,在webapi下json的传递方式已不同于之前的mvc了,介绍如下:

关于RC版WebAPI参数绑定问题

另一位朋友给出的链接指出了webapi下传值方式不同设计的原因:

 

引用Before sending a simple type, consider wrapping the value in a complex type. This gives you the benefits of model validation on the server side, and makes it easier to extend your model if needed.

在传递简单类型数据之前,考虑下是否把值包裹在一个复杂类型之中。这将使得你能够得到服务器端的模型验证,并能够根据需要今后轻松的拓展你的模型。

关于复杂类型和简单类型是怎么赋值的:

引用By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.
引用Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.

默认情况下,webapi尝试着从request url里获取简单类型数据,当然也可通过添加FromBody属性告知webapi从request body中读取你所需的数据。

webapi只读取response body一次,因此仅能从request body传递一个参数。如果你需要从request body里获取复杂类型值,可以在后台定义一个复杂类型对应传递的复杂类型的json数据来接收。

详细如下:

http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

rc版的webapi参数绑定器分为两种:

1.Model Binding
2.Formatters 
其中Model Binding仅从url中取值,这点是与mvc的model binding有区别的,formatters是从request的body中取值,并且是把整个body作为一个(不可为多个)对象解析为一个参数,后台需相对应的为前台传递的复杂类型定义一个对应的类。而mvc下的model binding系统会同时查询body和querystring下的数据并匹配。

 

posted on 2012-08-02 21:29  露水丛生  阅读(6241)  评论(0编辑  收藏  举报