1. 程式人生 > 其它 >Asp.Net Core報錯System.Text.Json.JsonException: A possible object cycle was detected which is not supp

Asp.Net Core報錯System.Text.Json.JsonException: A possible object cycle was detected which is not supp

Asp.Net Core報錯:System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32

檢測到不支援的可能物件迴圈。這可能是由於週期或物體深度大於最大允許深度32。

這是由於進行了物件巢狀或ef 查詢進行了預載入(關聯載入)引起的,就像解釋說的“物件迴圈”,層級太深解析不了。

解決方法:

新增 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包
Startup中新增服務,忽略迴圈引用
services.AddControllers().AddNewtonsoftJson(option =>
//忽略迴圈引用
option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
);

services.AddControllers().AddNewtonsoftJson(option =>
                //
忽略迴圈引用 option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore );


或者
通過另外建立一個類對查詢到的資料進行封裝後再返還。