简体   繁体   中英

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?

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

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM