无法在ASP.NET Core 2.0中发布原始类型 [英] Cannot post primitive types in asp.net core 2.0

查看:280
本文介绍了无法在ASP.NET Core 2.0中发布原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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)

那我的ID是否正确填充?

Then my id is populated correctly?

推荐答案

如果您的路线内容类型为([[FromBody] string id)那样直接从体内获取原始类型.> application/json ,因为mvc等待模型将json主体绑定到模型,而不是原始类型.

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. 将内容类型更改为纯文本/

  1. Changing content type to plain/text.

使用 StreamReader 获取原始令牌字符串.

Using StreamReader to get raw token string.

使用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 示例: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆