将json绑定到web api动作调用

时间:2014-09-02 11:20:13

标签: asp.net-web-api asp.net-web-api2

将JSON绑定到web api操作参数的正确方法是什么。例如,我有来自浏览器客户端的这个JSON

JSON

{"model":[{"firstName":"Vivian","lastName":"Richards","game":0},
          {"firstName":"Diego","lastName":"Maradona","game":"1"}]}

C#模型

public class Player {
    public int Id { get; set; }
    public int FirstName { get; set; }
    public int LastName { get; set; }
    public Game Game { get; set; }
}

Web API操作

// POST: api/Players
public IHttpActionResult PostPlayers(List<Player> model) { 
    //model bound is null here
    ....
}

原始请求

POST http://localhost:xxxxx/api/Players HTTP/1.1
Host: localhost:xxxxx
Connection: keep-alive
Content-Length: 120
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:xxxxx
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Content-Type: application/json
DNT: 1
Referer: http://localhost:xxxxx/assets/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,ms;q=0.6

{"model":[{"firstName":"Vivian","lastName":"Richards","game":0},{"firstName":"Diego","lastName":"Maradona","game":"1"}]}

为了帮助javascript CamelCase,我在 WebApiConfig.Register

中有以下内容
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

0 个答案:

没有答案