In previous article, I mentioned how to Deserialize XML string to Object in C# but in this article, I have mentioned how we can resolve error "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." in .NET Core 3 or .NET Core 6.
Recently, I was working on a project and had to pass JSON from controller to View using AJAX call, but got this error.
An unhandled exception occurred while processing the request.
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. Path: $.RaceFiles.Race.RaceFiles.Race.RaceFiles.Race.RaceFiles.Race.RaceFiles.Race.RaceFiles.Race.RaceFiles.Race.RaceFiles.Race.RaceFiles.Race.RaceFiles.Race.RaceFiles.
Here is what I saw in browser:
And this was the code in C# .NET Core Controller
public IActionResult GetRaceDetails(int id)
{
var str = new Race();
using (var raceRepo = new RaceService(_configuration))
{
str = raceRepo.GetRace(id);
}
return Json(str);
}
//while GetRace method is below
//
public Race GetRace(int id)
{
Race race = new Race();
using (var db = new EventManagementDatabase(_configuration))
{
race = db.Races.Include(a => a.RaceFiles).Where(a => a.ID == id).FirstOrDefault();
}
return race;
}
As you can see and understand from the issue, there is possible cycles of "RaceFiles" and "Race" table.
To resolve this error in .NET Core 6+, I navigated to "Program.cs
" and used below code
builder.Services.AddControllersWithViews()
.AddJsonOptions(options =>
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles
);
You will also need to add reference for:
using System.Text.Json.Serialization;
Just build and run, above error will be resolved.
If you are using .NET 5, then you can simply use below code in "Startup.cs
"
services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
again, we will need to add reference for 'System.Text.Json.Serialization
'
If you are using .NET Core 3 or less, then you will need to Install Below Nuget Package
Microsoft.AspNetCore.Mvc.NewtonsoftJson
then in startup.cs, you can use below code to resolve above error.
public void ConfigureServices(IServiceCollection services)
{
..........
.......
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
}
Hope it helps.
You may also like to read:
Using Appsettings.Json in Program.cs in .NET Core 6+
Return JSONResult in ASP.NET Core MVC
C# FromQuery Example in ASP.NET Core API
JWT Token Authentication using Web API in ASP.NET Core 6
Send Email in ASP.NET Core (With Attachments)