【问题标题】:Newtonsoft.Json System.InvalidOperationException: Synchronous operations are disallowedNewtonsoft.Json System.InvalidOperationException:不允许同步操作
【发布时间】:2020-11-23 03:28:38
【问题描述】:

我收到以下异常,但不知道如何解决。我不想设置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)

【问题讨论】:

  • docs.microsoft.com/en-us/dotnet/api/… 或等到/如果 Json.Net 支持 DeserializeAsync...(假设您不想自己阅读流)
  • 如果有效负载足够大以至于无法一次性读取 JSON 文档并且您无法将它们缩小,那么我认为您唯一真正的选择是将 AllowSynchronousIO 设置为true(甚至可能只是在需要时按请求),或者删除 Newtonsoft.Json 的使用并改用 System.Text.Json(或其他一些支持异步的序列化程序)。

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


【解决方案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

【讨论】:

猜你喜欢
  • 2021-11-01
  • 2023-01-27
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 2021-02-10
相关资源
最近更新 更多