我无法让模型绑定在新的 ASP.NET Web API 中工作。
我正在使用 jQuery 来发布我的帖子,客户端 JavaScript 看起来像这样:
function postJsonSettings() {
return {
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
xhrFields: {
withCredentials: true
}
};
}
function createCustomer(customer) {
var settings = postJsonSettings();
settings.data = JSON.stringify({ model: customer });
return $.ajax(Payboard.Util.getAbsoluteUrl('/api/customers'), settings);
}
结果请求如下所示:
POST /api/customers HTTP/1.1
Host: dev.payboard.com
Connection: keep-alive
Content-Length: 89
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://www.payboardapitest.com
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://www.payboardapitest.com/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
使用这样的 POST 有效负载:
{"model":{"ExternalCustomerId":"6c5015c8-d04e-4309-a493-ec0355d1b3a0","Name":"asdfasdf"}}
被调用的 C# Web API 方法如下所示:
// POST api/customers
public void Post([FromBody] CreateCustomerModel model)
{
// Do stuff
}
使用如下所示的 CreateCustomerModel:
public class CreateCustomerModel
{
[Required]
public string ExternalCustomerId { get; set; }
[Required]
public string Name { get; set; }
}
该CustomerController.Post()
方法被调用,并且其model
本身不为空,但ExternalCustomerId
andName
属性为空。
有什么明显的我做错了吗?