[英]System.Text.Json.JsonException: A possible object cycle was detected
[英]C# Circular reference. System.Text.Json.JsonException: A possible object cycle was detected .NET 5
我創建了一個 API,它返回一個對象 A,包含對象 B,對象 B 包含對象 A,請參見下面的示例:
public class Person() {
string Name {get;set;}
List<Schema> Schemas {get;set;}
}
public class Schema(){
List<Person> Persons {get;set;}
}
在 C# 中,這不會成為問題,並且不會捕獲異常(我在各處添加了 try-catch-statements。
問題:當我使用 swagger 嘗試該函數時,拋出給客戶端的異常為 500。
調用 API 的客戶端告訴我這是一個 cors 策略驗證。 我確信這不是問題,因為它在其他情況下運行良好。
要查看實際問題,我必須轉到 Windows“事件記錄器”。
從事件記錄器我發現這個:
異常:System.Text.Json.JsonException:檢測到可能的對象循環。 這可能是由於循環或對象深度大於最大允許深度 32。考慮在 JsonSerializerOptions 上使用 ReferenceHandler.Preserve 以支持循環。 在 System.Text.Json.ThrowHelper.ThrowJsonException_SerializerCycleDetected(Int32 maxDepth) 在 System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
為了解決循環引用的問題,我在配置(startup.cs,API)中添加了以下代碼:
services.AddMvc()
.AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
});
文檔可以在以下位置找到: https : //docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to?pivots=dotnet-5-0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.