關於.Net Core生成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.
阿新 • • 發佈:2021-07-15
此筆記記載了本人在.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; }); }