问题
I have this controller and I can't figure out, why name
parameter is null
public class DeviceController : ApiController
{
[HttpPost]
public void Select([FromBody]string name)
{
//problem: name is always null
}
}
here is my route mapping:
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}"
);
appBuilder.UseWebApi(config);
}
and here is my request:
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'}
I also tried to change body to plain string: 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
The request returns 204 which is ok, but the parameter is never mapped to a posted value.
*I'm using self hosted owin service.
回答1:
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
来源:https://stackoverflow.com/questions/36621229/webapi-action-paramer-is-null-when-using-frombody-attribute-and-post-method