c# - 使用文本/纯文本时不受支持的媒体类型
问题描述
尝试消费时收到以下响应text/plain
:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "|b28d0526-4ca38d2ff7036964."
}
控制器定义:
[HttpPost]
[Consumes("text/plain")]
public async Task<IActionResult> PostTrace([FromBody]string body)
{ ... }
HTTP 消息:
POST /api/traces HTTP/1.1
Content-Type: text/plain
User-Agent: PostmanRuntime/7.19.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 37d27eb6-92a0-4a6a-8b39-adf2c93955ee
Host: 0.0.0.0:6677
Accept-Encoding: gzip, deflate
Content-Length: 3
Connection: keep-alive
我能够很好地使用 JSON 或 XML。我错过了什么?
解决方案
参考:在 ASP.NET Core API 控制器中接受原始请求正文内容:
不幸的是,ASP.NET Core 不允许您仅通过方法参数以任何有意义的方式捕获“原始”数据。您需要以一种或另一种方式对 Request.Body 进行一些自定义处理以获取原始数据,然后对其进行反序列化。
您可以捕获原始 Request.Body 并从中读取原始缓冲区,这非常简单。
最简单、侵入性最小但不那么明显的方法是使用一种方法,该方法接受不带参数的 POST 或 PUT 数据,然后从 Request.Body 中读取原始数据:
[HttpPost] [Route("api/BodyTypes/ReadStringDataManual")] public async Task<string> ReadStringDataManual() { using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) { return await reader.ReadToEndAsync(); } }
要求:
POST http://localhost:5000/api/BodyTypes/ReadStringDataManual HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: text/plain Host: localhost:5000 Content-Length: 37 Expect: 100-continue Connection: Keep-Alive Windy Rivers with Waves are the best!
推荐阅读
- python - 如何使 QtableWidget 单元格按我想要的大小平方?
- mysql - MySQL 8 不使用提供的配置文件
- azure - ADF 映射数据流 byNames 表达式异常
- bash - 如何通过 bash shell 将数字字符串扩展为全范围数字?
- github - 为组织创建 github 存储库仅将维护者管理员权限分配给创建者
- java - 方法 void 与非 void 返回类型的最佳性能?
- openlayers - 如何在openlayer 6中添加导航历史控件,拖动和放大和缩小控件等?
- node.js - mongodb查询结果返回的对象的解构
- javascript - Angular 7 / Typescript根据创建的时间隐藏一个Div
- unity3d - DllNotFound 异常 - 有什么问题?