Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.

问题说明:

在.Net Core 3.0中进行了很多方面升级,常见错误之一:

Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.

出现错误的原因:

在.Net Core 3.0版本中,默认同步读取请求流 为 异步方式,默认不支持同步读取。

代码说明:

              using (StreamReader sr = new StreamReader(Request.Body, Encoding.UTF8))
                    {
                        //string content = sr.ReadToEnd();  //.Net Core 3.0 默认不再支持
                        string content = sr.ReadToEndAsync().Result;

解决方案:

1.使用异步读取请求上下文

 string content = sr.ReadToEndAsync().Result;

2.在配置中开启同步读取流操作

  //配置可以同步请求读取流数据
            services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true)
                .Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);

更多:

asp.netCore3.0区域和路由配置变化

在Asp.Net Core 3.0中如何使用 Newtonsoft.Json 库序列化数据  

Asp.Net Core Cookie使用,Asp.net Core Cookie操作失效