Fixing the error “A possible object cycle was detected” in different versions of ASP.NET Core

In order to fix the error:

System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.

You have at least two options:

  1. Avoiding circular references
  2. Ignoring circular references

I’ll assume that option 1 (which is usually ideal) it’s not viable for you.

Option 2 is literally a little statement in the Startup class, in the ConfigureServices method (this is for ASP.NET Core 6+):

services.AddControllers().AddJsonOptions(x =>
                x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

If you use ASP.NET Core 5:

services.AddControllers().AddJsonOptions(x =>
   x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);

If you are using ASP.NET Core 3.1 or less, you can do the following:

Install the library: Microsoft.AspNetCore.Mvc.NewtonsoftJson (install the corresponding version, if you have ASP.NET Core 3.1, you install version 3.1 of the library)

Then, in ConfigureServices:

services.AddControllers().AddNewtonsoftJson(x => 
 x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);


If you want to learn more about ASP.NET Core and C#, get one of my Udemy courses today:

  1. Building Applications with Angular 11 and ASP.NET Core 5:
  2. Programming in Blazor – ASP.NET Core 5:
  3. Building RESTful Web APIs with ASP.NET Core 3.1:
  4. Introduction to Concurrency in C# – Async and Paralellism:

Kind regards!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s