How to stop self-referencing loop in .Net Core Web API? c# entity-framework-core


I'm having some issues which I'm guessing are related to self-referencing using .NET Core Web API and Entity Framework Core. My Web API starting choking when I added .Includes for some navigation properties.

I found what appears to be a solution in the older Web API but I don't know how to implement the same thing for .NET Core Web API (I'm still in the early learning stages).

The older solution was sticking this in the Application_Start() of the Global.asax:

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;

I suspect this is handled in the StartUp's ConfigureService() method but I don't know much beyond there.

Or is there a more appropriate way to handle this issue?

3/1/2017 1:38:50 AM

Accepted Answer

Okay... I finally found some reference material on this. The solution is:

public void ConfigureServices(IServiceCollection services)

            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore


I got this from here

3/1/2017 3:29:18 AM

Popular Answer

If you are using ASP.NET Core 3.0, and experience that problem please install the NuGET package: Microsoft.AspNetCore.Mvc.NewtonsoftJson 3.0.0.

To replace the new System.Text.Json which does not yet have the Reference Loop Handling do this in the Startup.cs, make sure that in the ConfigureServices, is included:

If using the latest .Net Core 3.0 way:

services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

or the old way:

services.AddMvc(option => option.EnableEndpointRouting = false)
       .AddNewtonsoftJson(options => 
                 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow