Newtonsoft.Json System.InvalidOperationException: Synchronous operations are disallowed

Viewed 791

I am getting the following exception and I am not sure how to resolve it. I do not want to set AllowSynchronousIO = true. MS has made the decision starting with 3.0 to no longer allow synchronous by default and for good reason. So how do I get around this issue?

System.InvalidOperationException: Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.StreamReader.ReadBuffer(Span`1 userBuffer, Boolean& readToUserBuffer)
   at System.IO.StreamReader.ReadSpan(Span`1 buffer)
   at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)
   at Newtonsoft.Json.JsonTextReader.ReadData(Boolean append, Int32 charsRequired)
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonReader.ReadAndMoveToContent()
   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)
1 Answers

Using the Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream class as a wrapper around the stream solves the issue. This allows you to access a stream asynchronously and then expose the stream to a synchronous tool like Newtonsoft.Json without enabling SynchronousIO for the entire solution. MVC is getting around this error by using the FileBufferingReadStream class as well so it's well tested.

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webutilities.filebufferingreadstream?view=aspnetcore-3.1

Related