此筆記記載了本人在.Net Core 5.0環境下生成Json數據時
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.
的症狀、排查及解決方案。
環境
.Net Core版本:5.0
編譯器:Visual Studio 2019,Rider2021.1.3
症狀
在生成Json數據的時候會提示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.
的錯誤提示。
解決方案
造成此問題的原因是由於在生成Json對象的時候屬性的循環引用導致的。
可用如下方法進行解決
-
安裝 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包
可以從Nuget上進行下載並安裝
-
安裝完成后在 Startup.cs 文件中加入如下代碼
public void ConfigureServices(IServiceCollection services) { // .Net Core 5.0以下適用 services.AddMvc(options => { options.Filters.Add<ApiModelCheckFilterAttribute>(); }) .AddJsonOptions(options => { // 忽略屬性的循環引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); // .Net Core 5.0適用 services.AddMvc(options => { options.Filters.Add<ApiModelCheckFilterAttribute>(); }) .AddNewtonsoftJson(options => { // 忽略屬性的循環引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); }