c# – WebAPI POST [FromBody]没有绑定

我将JSON发布到WebAPI控制器,但是模型上的属性没有被绑定。

public void Post([FromBody] Models.Users.User model) {
    throw new Exception(model.Id.ToString());
}

原始请求如下:

POST http://diva2.local/siteapi/User HTTP/: diva2.local
Connection: keep-alive
Content-Length:: application/json, text/plain, */*
Origin: http://diva2.local
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.: application/json;charset=UTF: http://diva2.local/Users
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=: ISO-8859-1,utf-8;q=0.7,*;q=: .ASPXAUTH=4; __RequestVerificationToken=Rp_hUysjwCjmsxw2

{"Id":3,"FirstName":"DIVA2","LastName":"User1","Username":"diva1","IsApproved":true,"IsOnlineNow":true,"IsChecked":true}

我可以找到的每个例子告诉我这应该工作,但是model.Id == null。

但是,如果我将JSON更改为:

{User: {"Id":3,"FirstName":"DIVA2","LastName":"User1","Username":"diva1","IsApproved":true,"IsOnlineNow":true,"IsChecked":true}}

一切都正确绑定。

这似乎不正确。我想我可以接受JObject作为参数,并手动绑定,但是感觉像上面那样应该是Just Work(tm)?

更新:

我已经改变了返回模型的方法,我仍然收到null。

public Models.Users.User Post(Models.Users.User user) {
    return user;
}

回应:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-MiniProfiler-Ids: ["a0fab514-d725-4d8f-9021-4931dc06ec4a","fdeeb9a8-9e36-41d8-91d3-5348e880e193","c1b4cc86-d7c3-4497-8699-baac9fa79bf1"]
X-Powered-By: ASP.NET
Date: Tue, 21 May 2013 09:06:00 GMT
Content-Length: 4

null
您的请求中缺少Content-Type标头。

不幸的是,即使你已经检查了ModelState,我们也没有抛出任何错误信息。但是,好消息是,我们的新版本已经修复了此行为,您将看到基于状态代码的响应。

Web API需要Content-Type头来找出正确的格式化程序,以将身体反序列化为该操作上的参数。

http://stackoverflow.com/questions/16665815/webapi-post-frombody-not-binding

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – WebAPI POST [FromBody]没有绑定