

一、背景
- 环境:.Net Core 3.1
- 项目:WebApi
- 操作:读取Request.body的stream流
- 异常:
Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.

二、问题代码
var request = context.HttpContext.Request;
if (request.Method == "POST")
{
request.Body.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(request.Body, Encoding.UTF8))
{
var data = reader.ReadToEnd();
}
}

三、问题处理
1. 原因
2. 解决方法
解决方法1——配置支持同步读流
public void ConfigureServices(IServiceCollection services)
{
services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true)
.Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);
}
解决方法2——改为异步读流
var request = context.HttpContext.Request;
if (request.Method == "POST")
{
request.Body.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(request.Body, Encoding.UTF8))
{
var data = await reader.ReadToEndAsync();
}
}