Self referencing loop detected in ASP.NET Core

52,712

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"])
    );
}
Share:
52,712
sunil
Author by

sunil

Updated on July 09, 2022

Comments

  • sunil
    sunil almost 2 years

    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.

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

    How can we fix this in ASP.NET Core?

  • Daniel
    Daniel over 6 years
    to be clear, only the "ReferenceLoopHandling" line is required to resolve this issue.
  • Pablo Recalde
    Pablo Recalde about 6 years
    Before I found this solution, I tried to use that setting on the property that was causing issues, as an attribute [JsonProperty(ReferenceLoopHandling=ReferenceLoopHandling.Ig‌​nore)] but it had no effect. Can anyone explain why this solution didn't work in the first place?
  • Diego
    Diego about 6 years
    HI.. it does not work for me neither.. I only had to add "[JsonObject(IsReference = true)] " as a header on the class that gave me error and Works fine.
  • saviour123
    saviour123 almost 6 years
    Decorating the property with [JsonIgnore] solved it for me
  • Lion
    Lion over 5 years
    Setting ReferenceLoopHandling in JsonProperty on the attribute together with [JsonObject(IsReference = true)] solved the problem. The original answear with AddJsonOptions doesn't had any effect for me.
  • Saima
    Saima almost 5 years
    AddJsonOptions is the great solution that fixed incomplete json response issue without any hassle.
  • Hamza Dahmoun
    Hamza Dahmoun about 4 years
    you can avoid the self reference possibility by selecting only fields you need and exclude the fields that generate the reference looping