关于.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.

此笔记记载了本人在.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对象的时候属性的循环引用导致的。

可用如下方法进行解决

  1. 安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包 可以从Nuget上进行下载并安装
  2. 安装完成后在 Startup.cs 文件中加入如下代码
public void ConfigureServices(IServiceCollection services)
{
    // .Net Core 5.0以下适用
    services.AddMvc(options => { options.Filters.Add(); })
        .AddJsonOptions(options =>
        {
            // 忽略属性的循环引用
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });

    // .Net Core 5.0适用
    services.AddMvc(options => { options.Filters.Add(); })
        .AddNewtonsoftJson(options =>
        {
            // 忽略属性的循环引用
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });
}

Original: https://www.cnblogs.com/ykbb/p/15015265.html
Author: 一块白板
Title: 关于.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.

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/610424/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球