I'm posting very simple json data to a .net Core 2.0 API.
Why is it when I have a method like this:
public async Task<IActionResult> GetNewToken([FromBody]string id)
Then id is null, but if I encapsulate that in a model:
public class RandomViewModel
{
public string id { get; set; }
}
public async Task<IActionResult> GetNewToken([FromBody]RandomViewModel model)
Then my id is populated correctly?
You can in fact post a primitive type from request body, but you should not use the key/value, for example:
public async Task<IActionResult> LockUserByDate(Guid appUserId, [FromBody] string lockoutEnd)
Consider this action, when I test it in Postman if I use this for the body:
{
"lockoutEnd": "2018-03-15 16:30:35.4766052"
}
Then it dosen't bind but If I use only the value in the body, model bindler bind the value:
"2018-06-15 16:30:35.4766052"
You can not get primitive types from your body directly like ([FromBody] string id)
if your route content type is application/json
because mvc waits model to bind json body to model not primitive types.
There are some options to get primitive types from request body
Changing content type to plain/text.
Using StreamReader
to get raw token string.
Using MVC InputFormatter
StreamReader
Example:
[HttpPost]
public async Task<IActionResult> GetNewToken()
{
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
var token = await reader.ReadToEndAsync(); // returns raw data which is sent in body
}
// your code here
}
InputFormatter
example: https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With