可同時參見這篇文章 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 Binding2.Formatters 其中Model Binding僅從url中取值,這點是與mvc的model binding有區別的,formatters是從request的body中取值,並且是把整個body作為一個(不可為多個)對象解析為一個參數,後台需相對應的為前台傳遞的複雜類型定義一個對應的類。而mvc下的model binding系統會同時查詢body和querystring下的資料並匹配。
rc版的webapi參數綁定器分為兩種:
1.Model Binding