Newtonsoft.Json System.InvalidOperationException:不允许进行同步操作

时间:2020-10-12 16:50:55

标签: c# asp.net-core json.net

我收到以下异常,但不确定如何解决。我不想设置AllowSynchronousIO = true。 MS已决定从3.0开始,默认情况下不再允许同步,这是有充分理由的。那么如何解决这个问题呢?

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 个答案:

答案 0 :(得分:1)

使用Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream类作为流的包装器解决了该问题。这使您可以异步访问流,然后将该流公开给Newtonsoft.Json之类的同步工具,而无需为整个解决方案启用SynchronousIO。 MVC也通过使用FileBufferingReadStream类来解决此错误,因此已经过充分测试。

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