关于.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<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;
            });
    }
    
posted @ 2021-07-15 14:10  一块白板  阅读(2330)  评论(0编辑  收藏  举报