AspNetCore SignalR : Json 实体循环引用问题解决方案

大概报错信息

一般是 两个实体 互相引用造成的死循环, (你中有我,我中有你,程序会一直递归下去)
设置 忽略引用, 即可解决

System.Text.Json.JsonException: 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 64. Consider using ReferenceHandler.Prese
rve on JsonSerializerOptions to support cycles.

SignalR

NuGet 搜索并下载
Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson

// 在Startup ConfigureServices 中设置
services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
 {
     options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 }); 

Asp.Net (api / mvc)

NuGet 搜索并下载
Microsoft.AspNetCore.Mvc.NewtonsoftJson

// 在Startup ConfigureServices 中设置
services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});

单独使用 Newtonsoft.Json 的时候

无需引用其他包, 直接设置即可
可以自己封装一个转string的方法, 每次调用传实体, 无需多次设置忽略

var model = new User(); // 用来举例的实体

var jsonSettings = new JsonSerializerSettings()
{
    // 设置忽略
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
// 转string
var jsonData = JsonConvert.SerializeObject(model, jsonSettings);

_logger.LogInformation(jsonData);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值