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

Courses

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

  1. Building Applications with React 17 and ASP.NET Core 6: https://www.udemy.com/course/building-applications-with-react-and-aspnet-core/?couponCode=SEPTEMBER2021
  2. Building Applications with Angular 11 and ASP.NET Core 5: https://www.udemy.com/course/building-applications-with-angular-and-aspnet-core/?couponCode=SEPTEMBER2021
  3. Programming in Blazor – ASP.NET Core 5: https://www.udemy.com/course/programming-in-blazor-aspnet-core/?couponCode=SEPTEMBER2021
  4. Building RESTful Web APIs with ASP.NET Core 3.1: https://www.udemy.com/course/building-restful-web-apis-with-aspnet-core/?couponCode=SEPTEMBER2021
  5. Introduction to Concurrency in C# – Async and Paralellism: https://www.udemy.com/course/introduction-to-concurrency-in-c-async-and-paralellism/?couponCode=SEPTEMBER2021

Kind regards!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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