消费文字/纯文字时,媒体类型不受支持

时间:2019-11-18 09:29:19

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

当尝试使用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。我想念什么?

1 个答案:

答案 0 :(得分:1)

参考:Accepting Raw Request Body Content in ASP.NET Core API Controllers

  

不幸的是,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!