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

WebApi - action paramer is null when using [FromBody] attribute and POST method

我有这个控制器,但我想不通,为什么 name 参数为空

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

请求 returns 204 没问题,但参数从未映射到发布值。

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

在第一个示例中,当 [FromBody] 属性告诉活页夹查找简单类型时,您使用了复杂的 object {'name':'hello'}

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

使用[FromBody]

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

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

在此示例中,Web API 将使用 media-type 格式化程序从请求 body 中读取名称的值。这是一个示例客户端请求。

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 至 select 格式化程序。在此示例中,内容类型是 "application/json",请求 body 是原始 JSON 字符串(不是 JSON object)。

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

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

此规则的原因是请求 body 可能存储在只能读取一次的 non-buffered 流中。

来源:Parameter Binding in ASP.NET Web API