无法在ASP.NET Core 2.0中发布原始类型

编程入门 行业动态 更新时间:2024-10-23 09:33:27
本文介绍了无法在ASP.NET Core 2.0中发布原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm posting very simple json data to a 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?

推荐答案

如果您的路线内容类型为 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

  • 将内容类型更改为纯文本/

  • 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 示例: weblog.west-wind/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-控制器

  • 更多推荐

    无法在ASP.NET Core 2.0中发布原始类型

    本文发布于:2023-11-16 09:37:12,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1603101.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:原始   类型   NET   ASP   Core

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!