Dav*_*New 6 c# asp.net-core-mvc asp.net-core
尝试消费时收到以下响应text/plain:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "|b28d0526-4ca38d2ff7036964."
}
Run Code Online (Sandbox Code Playgroud)
控制器定义:
[HttpPost]
[Consumes("text/plain")]
public async Task<IActionResult> PostTrace([FromBody]string body)
{ ... }
Run Code Online (Sandbox Code Playgroud)
HTTP 消息:
[HttpPost]
[Consumes("text/plain")]
public async Task<IActionResult> PostTrace([FromBody]string body)
{ ... }
Run Code Online (Sandbox Code Playgroud)
我能够很好地使用 JSON 或 XML。我错过了什么?
小智 9
参考:在 ASP.NET Core API 控制器中接受原始请求正文内容:
不幸的是,ASP.NET Core 不允许您仅通过方法参数以任何有意义的方式捕获“原始”数据。您需要以一种或另一种方式对 Request.Body 进行一些自定义处理以获取原始数据,然后对其进行反序列化。
您可以捕获原始 Request.Body 并从中读取原始缓冲区,这非常简单。
最简单和最少侵入性但不是那么明显的方法是使用一种方法来接受不带参数的 POST 或 PUT 数据,然后从 Request.Body 读取原始数据:
Run Code Online (Sandbox Code Playgroud)[HttpPost] [Route("api/BodyTypes/ReadStringDataManual")] public async Task<string> ReadStringDataManual() { using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) { return await reader.ReadToEndAsync(); } }要求:
Run Code Online (Sandbox Code Playgroud)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!
| 归档时间: |
|
| 查看次数: |
3776 次 |
| 最近记录: |