【问题标题】:Self referencing loop detected in ASP.NET Core [duplicate]在 ASP.NET Core 中检测到自引用循环 [重复]
【发布时间】:2016-04-17 15:34:08
【问题描述】:

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

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

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

【问题讨论】:

  • the answer。它应该可以解决您的问题。
  • 你可以看看我在 “Self Referencing Loop Detected” exception with JSON.Net 页面上的回答。
  • “重复”问题只是部分重复,因为它不涉及将其集成到 ASP.NET Core 中的特殊性。正如公认的答案所说,Core 中的情况发生了变化,因此“重复”问题的答案不起作用。

标签: json.net asp.net-core asp.net-core-mvc


【解决方案1】:

与 ASP.NET Core(以前的 Asp.Net 5)相比,在 ASP.NET 4 中处理自引用循环的方式没有区别。您在帖子中引用的问题中概述的原则仍然适用。但是,鉴于配置和引导应用程序的新方法,在 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"])
    );
}

【讨论】:

  • 要清楚,解决此问题只需要“ReferenceLoopHandling”行。
  • 在找到此解决方案之前,我尝试在导致问题的属性上使用该设置作为属性[JsonProperty(ReferenceLoopHandling=ReferenceLoopHandling.Ignore)],但它没有效果。谁能解释为什么这个解决方案一开始就不起作用?
  • 嗨..它对我也不起作用..我只需要添加“[JsonObject(IsReference = true)]”作为给我错误的类的标题并且工作正常。
  • [JsonIgnore]装饰房产为我解决了这个问题
  • 在属性JsonProperty 中设置ReferenceLoopHandling[JsonObject(IsReference = true)] 解决了这个问题。 AddJsonOptions 的原始答案对我没有任何影响。
猜你喜欢
  • 2017-10-30
  • 2016-12-15
  • 2020-03-29
  • 2013-10-28
  • 2012-11-10
  • 1970-01-01
  • 2016-02-15
  • 2014-02-05
  • 1970-01-01
相关资源
最近更新 更多