无法在asp.net core 2.0中发布原始类型

问题描述 投票:2回答:2

我将非常简单的json数据发布到.net Core 2.0 API。

为什么我有这样的方法:

public async Task<IActionResult> GetNewToken([FromBody]string id)

然后id为null,但如果我将其封装在模型中:

public class RandomViewModel
{
    public string id { get; set; }
}

public async Task<IActionResult> GetNewToken([FromBody]RandomViewModel model)

然后我的id正确填充?

c# asp.net-core
2个回答
2
投票

如果您的路由内容类型是([FromBody] string id),则无法直接从您的身体获取原始类型,如application/json,因为mvc等待模型将json主体绑定到模型而不是基本类型。

有一些选项可以从请求体中获取原始类型

  1. 将内容类型更改为纯文本/文本。
  2. 使用StreamReader获取原始令牌字符串。
  3. 使用MVC InputFormatter

StreamReader示例:

[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例子:https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers


4
投票

实际上,您可以从请求正文中发布基本类型,但不应使用键/值,例如:

public async Task<IActionResult> LockUserByDate(Guid appUserId, [FromBody] string lockoutEnd)

考虑一下这个动作,当我在Postman中测试它时,如果我将它用于身体:

{
 "lockoutEnd": "2018-03-15 16:30:35.4766052"
}

然后它不会绑定但如果我只使用正文中的值,模型绑定器绑定值:

"2018-06-15 16:30:35.4766052"

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.