Asp.net web api 将json绑定到web api操作调用
将JSON绑定到web api操作参数的正确方法是什么。例如,我有一个来自浏览器客户端的JSON JSONAsp.net web api 将json绑定到web api操作调用,asp.net-web-api,asp.net-web-api2,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"}]} public class Player { public int Id { get; set; } publi
{"model":[{"firstName":"Vivian","lastName":"Richards","game":0},
{"firstName":"Diego","lastName":"Maradona","game":"1"}]}
public class Player {
public int Id { get; set; }
public int FirstName { get; set; }
public int LastName { get; set; }
public Game Game { get; set; }
}
C#model
{"model":[{"firstName":"Vivian","lastName":"Richards","game":0},
{"firstName":"Diego","lastName":"Maradona","game":"1"}]}
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
....
}
为了帮助解决这个问题,我在WebApiConfig.Register中提供了以下内容
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
您的json应该是
[{“firstName”:“Vivian”,“lastName”:“Richards”,“game”:0},{“firstName”:“Diego”,“lastName”:“马拉多纳”,“game”:“1”}]
。请参阅我的回答:@KhanhTO您对webapi控制器期望json的方式是正确的。它确实有效。但这并不能完全解决我的问题,因为数据来自backbone.js“save”。既然这是另一个问题,我将在这里结束这个问题。