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

后端 未结 1 570
眼角桃花
眼角桃花 2021-01-21 20:27

I have this controller and I can\'t figure out, why name parameter is null

public class DeviceController : ApiController
{
    [HttpPost]
    public         


        
相关标签:
1条回答
  • 2021-01-21 21:29

    In the first example You were using a complex object {'name':'hello'} when the [FromBody] attribute told the binder to look for a simple type.

    In the second example your provided value in the body could not be interpreted as a simple type as it was missing quotation marks "hello"

    Using [FromBody]

    To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:

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

    In this example, Web API will use a media-type formatter to read the value of name from the request body. Here is an example client request.

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

    When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

    At most one parameter is allowed to read from the message body. So this will not work:

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

    The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

    Source: Parameter Binding in ASP.NET Web API

    0 讨论(0)
提交回复
热议问题