FromBody string parameter is giving null
Referencing Parameter Binding in ASP.NET Web API
Using [FromBody]
To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:
[Route("Edit/Test")] [HttpPost] public IHttpActionResult Test(int id, [FromBody] string jsonString) { ... }
In this example, Web API will use a media-type formatter to read the value of jsonString from the request body. Here is an example client request.
POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1 User-Agent: Fiddler Host: localhost:8000 Content-Type: application/json Content-Length: 6 "test"
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).
In the above example no model is needed if the data is provided in the correct format in the body.
For URL encoded a request would look like this
POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
User-Agent: Fiddler
Host: localhost:8000
Content-Type: application/x-www-form-urlencoded
Content-Length: 5
=test
By declaring the jsonString parameter with [FromBody]
you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class
public class MyModel
{
public string Key {get; set;}
}
[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] MyModel model)
{
... model.Key....
}
and a sent JSON like
{
key: "value"
}
Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request
in the controller. The HttpContext.Request.Body
property gives you the content stream or you can access the form data via HttpContext.Request.Forms
.
I personally prefer the model binding because of the type safety.
When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:
"test"
Based on https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers
Similar answer string value is Empty when using FromBody in asp.net web api