由于ASP.Net Core在3.0版本中禁用了同步读取Request.Body,所以会引发异常,网上大多数教程都是如何将禁用同步读取流的选项重新启用,由于微软的官方文档中已经警告了同步读取Request.Body会引发内存泄漏,所以需要用推荐的方式读取Request.Body,也就是使用PipeReader来读取,下面封装了一个方法和一个示例供参考:
/// <summary> /// 获取请求头字节 /// </summary> /// <param name="token"></param> /// <param name="reader"></param> /// <returns></returns> [NonAction] private async Task<byte[]> GetRequestBodyBytesAsync(CancellationToken token, PipeReader reader) { byte[] bodyBytes = null; while (!token.IsCancellationRequested) { ReadResult readResult = await reader.ReadAsync(); if (readResult.IsCompleted) { var buffer = readResult.Buffer; bodyBytes = buffer.ToArray(); break; } else { var buffer = readResult.Buffer; reader.AdvanceTo(buffer.Start, buffer.End); } } return bodyBytes; }
使用示例:
[HttpPost] public async Task<IActionResult> TestAction() { var bodyBytes = await GetRequestBodyBytesAsync( HttpContext.RequestAborted, Request.BodyReader); //如果内容是字符串则转换成字符串,如果是文件则是文件的Byte数组 string content = Encoding.UTF8.GetString(bodyBytes); Console.WriteLine("Http Request Body: {0}", content); return Ok(); }