Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot post primitive types in asp.net core 2.0

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?

like image 671
Robbie Mills Avatar asked Mar 03 '18 09:03

Robbie Mills


2 Answers

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"

enter image description here

like image 105
Hamid Mosalla Avatar answered Nov 07 '22 11:11

Hamid Mosalla


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

  1. Changing content type to plain/text.

  2. Using StreamReader to get raw token string.

  3. 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

like image 30
hasan Avatar answered Nov 07 '22 10:11

hasan