JSON infinite loops in ASP.NET

Posted by Joe Enos on April 08, 2021 · 1 min read

If you accidentally (or purposely) have an infinite loop in an object, where it has a reference that points back to itself, when you try to return that object as JSON in ASP.NET, you get an error:

JsonSerializationException: Self referencing loop detected for property...

To avoid that, you can add a line to your Startup ConfigureServices method:

// dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson

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