WebAPI POST [FromBody]未绑定 [英] WebAPI POST [FromBody] not binding
问题描述
我正在将JSON发布到WebAPI控制器,但是未绑定模型上的属性.
I'm posting JSON to a WebAPI controller, but the properties on the model are not being bound.
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
.
Every example I can find tells me this should work, but model.Id == null
.
但是,如果我将JSON更改为:
However, if I change the JSON to:
{User: {"Id":3,"FirstName":"DIVA2","LastName":"User1","Username":"diva1","IsApproved":true,"IsOnlineNow":true,"IsChecked":true}}
一切正常绑定.
这似乎不正确.我想我可以接受 JObject
作为参数,并将其手动绑定,但是感觉上面的代码应该可以正常工作(tm)?
This doesn't seem correct. I guess I could accept JObject
as the parameter, and bind it up manually, but it feels like the above should Just Work (tm)?
更新:
我已经更改了返回模型的方法,但我仍然收到null.
I've changed the method to return the model, and I still receive 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
推荐答案
我的用户模型没有无参数的构造函数.
My user model did not have a parameter-less constructor.
这篇关于WebAPI POST [FromBody]未绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!