在 ASP.NET 核心中检测到自引用循环

Self referencing loop detected in ASP.NET Core

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

在ASP.NET 4中我们曾经这样全局修复它: JSON.NET Error Self referencing loop detected for type

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

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

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"])
    );
}