首页 > 解决方案 > 使用文本/纯文本时不受支持的媒体类型

问题描述

尝试消费时收到以下响应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。我错过了什么?

标签: c#asp.net-coreasp.net-core-mvc

解决方案


参考:在 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!

推荐阅读