gpt4 book ai didi

c# - Web Api - 使用 [FromBody] 属性和 POST 方法时操作参数为空

转载 作者:行者123 更新时间:2023-11-30 20:20:29 31 4
gpt4 key购买 nike

我有这个 Controller ,但我想不通,为什么 name 参数为 null

public class DeviceController : ApiController
{
[HttpPost]
public void Select([FromBody]string name)
{
//problem: name is always null
}
}

这是我的路线图:

public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}"
);

appBuilder.UseWebApi(config);
}

这是我的要求:

POST http://localhost:9000/api/device/Select HTTP/1.2
User-Agent: Fiddler
Host: localhost:9000
Content-Length: 16
Content-Type: application/json

{'name':'hello'}

我还尝试将正文更改为纯字符串:hello

POST http://localhost:9000/api/device/Select HTTP/1.2
User-Agent: Fiddler
Host: localhost:9000
Content-Length: 5
Content-Type: application/json

hello

请求返回 204,这是正常的,但参数从未映射到发布的值。

*我正在使用自托管的 o​​win 服务。

最佳答案

在第一个示例中,当 [FromBody] 属性告诉 Binder 寻找一个简单的对象时,您使用了一个复杂的对象 {'name':'hello'}类型。

在第二个示例中,您在正文中提供的值无法解释为简单类型,因为它缺少引号 "hello"

使用 [FromBody]

要强制 Web API 从请求正文中读取简单类型,请将 [FromBody] 属性添加到参数中:

public HttpResponseMessage Post([FromBody] string name) { ... }

在此示例中,Web API 将使用媒体类型格式化程序从请求正文中读取名称的值。这是一个示例客户端请求。

POST http://localhost:5076/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:5076
Content-Type: application/json
Content-Length: 7

"Alice"

当参数具有 [FromBody] 时,Web API 使用 Content-Type header 来选择格式化程序。在此示例中,内容类型为“application/json”,请求正文为原始 JSON 字符串(而非 JSON 对象)。

最多允许从消息正文中读取一个参数。所以这是行不通的:

// Caution: Will not work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

此规则的原因是请求正文可能存储在只能读取一次的非缓冲流中。

来源:Parameter Binding in ASP.NET Web API

关于c# - Web Api - 使用 [FromBody] 属性和 POST 方法时操作参数为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36621229/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com