JSON infinite loops in ASP.NET

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;
    });

Comments

Popular posts from this blog

C# Record Serialization

Add timestamp to photo using ImageMagick

Read/write large blob to SQL Server from C#