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


#Accident scene

In the asp.net core web API project, when reading the stream stream of request.body, the following error is reported:

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

The code is as follows:

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();
    }
}

#Solution

The synchronous reading method of the body needs to be configured in configureservices to allow synchronous reading of IO streams. Otherwise, an exception may be thrown. Call readasync or set allowsynchronous IO to true instead.
configure according to the managed service used or directly use the asynchronous reading method.

public void ConfigureServices(IServiceCollection services)
{
	//other
	
	services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true)
                .Configure<IISServerOptions>(x=>x.AllowSynchronousIO = true);
}

Read More: