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:
- Avoiding circular references
- 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:
- Building Applications with React 17 and ASP.NET Core 6: https://www.udemy.com/course/building-applications-with-react-and-aspnet-core/?couponCode=SEPTEMBER2021
- Building Applications with Angular 11 and ASP.NET Core 5: https://www.udemy.com/course/building-applications-with-angular-and-aspnet-core/?couponCode=SEPTEMBER2021
- Programming in Blazor – ASP.NET Core 5: https://www.udemy.com/course/programming-in-blazor-aspnet-core/?couponCode=SEPTEMBER2021
- Building RESTful Web APIs with ASP.NET Core 3.1: https://www.udemy.com/course/building-restful-web-apis-with-aspnet-core/?couponCode=SEPTEMBER2021
- Introduction to Concurrency in C# – Async and Paralellism: https://www.udemy.com/course/introduction-to-concurrency-in-c-async-and-paralellism/?couponCode=SEPTEMBER2021
For net core 5. If we put Preserve, the JSON results are adjusted like in this question on SO: https://stackoverflow.com/questions/65980999/asp-net-core-5-returning-json-adding-id-and-values-properties
😦 Not really the way to deal with “A possible object cycle was detected…” This is not really as same as Ignore’s behaviour. Do you know any alternative for Net Core 5? Many thanks
You can apply the same solution of .NET 3.1, it’s the same result like the “Ignore” option.