In order to fix the error:
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
You have at least two options:
Avoiding circular references
Ignoring circular references
I’ll assume that option 1 (which is usually ideal) it’s not viable for you.
Option 2 is literally a little statement in the Startup class, in the ConfigureServices method (this is for ASP.NET Core 6+):
services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
If you use ASP.NET Core 5:
services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
If you are using ASP.NET Core 3.1 or less, you can do the following:
Install the library: Microsoft.AspNetCore.Mvc.NewtonsoftJson (install the corresponding version, if you have ASP.NET Core 3.1, you install version 3.1 of the library)
Then, in ConfigureServices:
services.AddControllers().AddNewtonsoftJson(x =>
x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
修復不同版本的 ASP.NET Core 中“檢測到可能的對象循環”錯誤
為了修復錯誤:
System.Text.Json.JsonException: 檢測到可能的對象循環。這可能是由於循環或對象深度大於最大允許深度 32。考慮在 JsonSerializerOptions 上使用 ReferenceHandler.Preserve 以支持循環。
你至少有兩個選擇:
避免循環引用
忽略循環引用
我會假設選項 1(通常是理想的)對您來說不可行。
選項 2 實際上是 Startup 類中的一個小聲明,在 ConfigureServices 方法中(這是針對ASP.NET Core 6+):
services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
如果您使用ASP.NET Core 5:
services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
如果您使用的是ASP.NET Core 3.1 或更低版本,則可以執行以下操作:
安裝庫:Microsoft.AspNetCore.Mvc.NewtonsoftJson(安裝對應版本,如果有ASP.NET Core 3.1,則安裝3.1版本的庫)
然後,在配置服務中:
services.AddControllers().AddNewtonsoftJson(x =>
x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);