C# FromBody 未绑定字符串参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11515319/
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-09 18:08:59  来源:igfitidea点击:

FromBody not binding string parameter

c#.netasp.net-web-api

提问by Jordan Crittenden

I have an issue similar to ASP.NET MVC 4 RC Web API Parameter Binding Issue, but I'm trying to solve it by using the [FromBody] attribute.

我有一个类似于ASP.NET MVC 4 RC Web API Parameter Binding Issue 的问题,但我正在尝试使用 [FromBody] 属性来解决它。

Fiddler reports the following request (excluding irrelevant bits like User Agent String)

Fiddler 报告以下请求(排除用户代理字符串等不相关位)

PUT http://localhost:82/api/account/shoppinglistitems HTTP/1.1
Host: localhost:82
Connection: keep-alive
Content-Length: 11
Origin: http://localhost:3000
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/javascript, */*; q=0.01

query=apple

My controller action is

我的控制器动作是

[HttpPut]
public ShoppingListItemWebModel CreateShoppingListItem([FromBody]string query) {
    // query is null
}

I could wrap the parameter in a complex type, but that seems like a hack to fix the issue. Or I could put the query in the URI, but that doesn't fit the pattern of the rest of the API. Is it possible to do it this way? If so, where is my mistake?

我可以将参数包装在复杂类型中,但这似乎是解决问题的一种方法。或者我可以将查询放在 URI 中,但这不符合 API 其余部分的模式。可以这样做吗?如果是这样,我的错误在哪里?

采纳答案by Filip W

change your request to be

改变你的要求

PUT http://localhost:82/api/account/shoppinglistitems HTTP/1.1
Host: localhost:82
Connection: keep-alive
Content-Length: 11
Origin: http://localhost:3000
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/javascript, */*; q=0.01

=apple

notice the lack of "query"

注意缺少“查询”

回答by tsemer

If you're using AngularJS instead of jQuery you might want to opt for the following alternative, since AngularJS uses content type application/jsonby default.

如果您使用 AngularJS 而不是 jQuery,您可能需要选择以下替代方案,因为 AngularJSapplication/json默认使用内容类型。

PUT http://localhost:82/api/account/shoppinglistitems HTTP/1.1
Host: localhost:82
Connection: keep-alive
Content-Length: 7
Origin: http://localhost:3000
Content-Type: application/json
Accept: application/json, text/javascript, */*; q=0.01

'apple'

Notice that the value is wrapped in string quotes (either single or double).

请注意,该值包含在字符串引号中(单引号或双引号)。