在 ASP.NET Core 中检测到自引用循环 [英] Self referencing loop detected in ASP.NET Core

查看:29
本文介绍了在 ASP.NET Core 中检测到自引用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用 ASP.NET Core Newsoft JSON.NET 序列化某些域对象时,它抛出异常,因为它正在检测自引用循环.

When I try to serialize some domain objects using ASP.NET Core Newsoft JSON.NET it is throwing an exception because it is detecting a self referencing loop.

在 ASP.NET 4 中,我们曾经通过这种方式全局修复它:检测到类型的 JSON.NET 错误自引用循环

In ASP.NET 4 we used to fix it globally this way: JSON.NET Error Self referencing loop detected for type

我们如何在 ASP.NET Core 中解决这个问题?

How can we fix this in ASP.NET Core?

推荐答案

与 ASP.NET Core(以前称为 Asp.Net 5)相比,ASP.NET 4 中处理自引用循环的方式没有区别.您在帖子中引用的问题中概述的原则仍然适用.但是,鉴于配置和引导应用程序的新方法,在 ASP.NET Core 中设置此属性显然略有不同:

There is no difference in the way self-referencing loops are handled in ASP.NET 4 compared to ASP.NET Core (previously Asp.Net 5). The principles outlined in the question you referenced in your post still apply. However, setting this property in ASP.NET Core is obviously slightly different, given the new method of configuring and bootstrapping the app:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(options => {
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
    services.AddEntityFramework().AddSqlServer().AddDbContext<IvoryPacketDbContext>(
        options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])
    );
}

这篇关于在 ASP.NET Core 中检测到自引用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆