C# WebAPI POST [FromBody] 未绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16665815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:37:13  来源:igfitidea点击:

WebAPI POST [FromBody] not binding

c#asp.net-web-api

提问by mattdwen

I'm posting JSON to a WebAPI controller, but the properties on the model are not being bound.

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

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

The raw request is as follows:

原始请求如下:

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}

Every example I can find tells me this should work, but model.Id == null.

我能找到的每个例子都告诉我这应该有效,但是model.Id == null.

However, if I change the JSON to:

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

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

everything binds correctly.

一切都正确绑定。

This doesn't seem correct. I guess I could accept JObjectas the parameter, and bind it up manually, but it feels like the above should Just Work (tm)?

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

Update:

更新:

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;
}

And the response:

和回应:

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

采纳答案by mattdwen

My user model did not have a parameter-less constructor.

我的用户模型没有无参数构造函数。

回答by Darin Dimitrov

The following works perfectly fine for me:

以下对我来说非常好:

Model:

模型:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Username { get; set; }
    public bool IsApproved { get; set; }
    public bool IsOnlineNow { get; set; }
    public bool IsChecked { get; set; }
}

Controller:

控制器:

public class ValuesController : ApiController
{
    public User Post(User user)
    {
        return user;
    }
}

Request:

要求:

POST http://example.com/api/values HTTP/1.1
Connection: keep-alive
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Host: localhost:8816
Content-Length: 125

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

Response:

回复:

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
Date: Tue, 21 May 2013 08:59:02 GMT
Content-Length: 125

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

As you can see everything is bound fine and dandy without the Userprefix in the request JSON payload.

正如您所看到的User,在请求 JSON 负载中没有前缀的情况下,一切都很好。

Be careful with the model.Id, because idmight have a special meaning if you are using it in your route definitions as being part of the route. Do not confuse the 2 things (route parameters and those coming from the request body payload).

小心使用model.Id, 因为id如果您在路由定义中将它用作路由的一部分,它可能具有特殊含义。不要混淆两件事(路由参数和来自请求正文有效负载的参数)。

回答by Kiran Challa

You are missing the Content-Typeheader in your Request.

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

Unfortunately even if you had checked for ModelState, we are not throwing any error information. However, the good news is that this behavior has been fixed for our coming release and you would see a 415 status code based response.

不幸的是,即使您检查了 ModelState,我们也不会抛出任何错误信息。然而,好消息是我们即将发布的版本已修复此行为,您将看到基于 415 状态代码的响应。

Web API requires the Content-Type header to find out the right formatter to deserialize the body to the parameter on the action.

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

回答by armstb01

I found that my class had internal setters on all the properties.

我发现我的班级在所有属性上都有内部设置器。

Changing public <property> {get; internal set;}to public <property> {get; set;}

更改 public <property> {get; internal set;}public <property> {get; set;}

fixed my issue

修复了我的问题

回答by Chris Chevalier

I had the Serializableand xmlElementtags on my class. Even though I specified JSON as the content type in requests and passed a JSON string it wouldn't work till those were removed... It also appears only the serializableattribute was causing the issue.

我的课上有SerializablexmlElement标签。即使我将 JSON 指定为请求中的内容类型并传递了一个 JSON 字符串,但在删除这些字符串之前它不会工作......它似乎也只有serializable属性导致了问题。