44

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?

3
  • Look at the answer. It should solve your problem. Commented Jan 12, 2016 at 23:37
  • You might have a look at my answer on “Self Referencing Loop Detected” exception with JSON.Net page. Commented Jul 8, 2018 at 20:36
  • The "duplicate" question is only a partial duplicate, since it doesn't refer to the particularities of integrating this in ASP.NET Core. As the accepted answer says, things have changed in Core so the answer of the "duplicate" question wouldn't work. Commented Aug 9, 2018 at 9:06

1 Answer 1

109

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"])
    );
}
Sign up to request clarification or add additional context in comments.

7 Comments

to be clear, only the "ReferenceLoopHandling" line is required to resolve this issue.
Before I found this solution, I tried to use that setting on the property that was causing issues, as an attribute [JsonProperty(ReferenceLoopHandling=ReferenceLoopHandling.Ignore)] but it had no effect. Can anyone explain why this solution didn't work in the first place?
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.
Decorating the property with [JsonIgnore] solved it for me
you can avoid the self reference possibility by selecting only fields you need and exclude the fields that generate the reference looping
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.