.net core api在返回json数据时,出现错误,转json不断shi循环。

1,错误信息:

A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.Data.User.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users

翻译后的意思:

检测到可能的对象循环。这要么是由于存在循环,要么是因为对象深度超过了允许的最大深度 32。请考虑在 JsonSerializerOptions 中使用 ReferenceHandler.Preserve 来支持循环。路径:$.Data.User.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users.Company.Users

2,解决方法:

在添加控制器后面加AddJsonOptions()方法,参考下面代码:

cs 复制代码
// 2. 添加控制器
builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

谢谢观看,不是在改Bug路上,就是制造bug缔造者!

相关推荐
海盗12347 天前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
啊这啊这 六弦之首14 天前
.NET Core跨平台的奥秘[中篇]:复用之殇
.netcore
心念枕惊14 天前
.NET CORE 授权进阶-角色、策略与动态权限实现
java·前端·.netcore
完美火龙篇 四月的友16 天前
通俗易懂,什么是.NET?什么是.NET Framework?什么是.NET Core?
.net·.netcore
时代的狂1 个月前
如何理解 C# 的 async 和 await
c#·.netcore·async·await
尼米棕熊1 个月前
.NET CORE认证模块-注册方案与请求认证探究
.netcore
鸠摩智首席音效师2 个月前
如何在 macOS 上安装 .NET Core ?
macos·.netcore
宝桥南山2 个月前
Microsoft Agent Framework(MAF) - 如何将workflow或者A2A client转换成一个AI Agent
microsoft·ai·微软·aigc·.net·.netcore
滴滴答答哒3 个月前
.NET Core 基于 AOP + Polly 实现数据库死锁自动重试
数据库·.netcore·sqlsugar
.NET修仙日记3 个月前
.NET EFCore批量插入性能优化实战:30秒 → 0.5秒
性能优化·c#·.net·.netcore·微软技术·efcore·踩坑实录