JsonException: A possible object cycle was detected which is not supported

Today in this article, we will cover below aspects,

Issue Description

ASP.NET Core application gives below runtime error,

System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.

A possible object cycle was detected

I got the above error for ASP.NET Core 3.1 with EFCore and but this error could possibly exist for 3.* and above any version.

Resolution

I found this error more due to the default JSON serializer used in ASP.NET Core 3.0 and the above version.

ASP.NET Core 3.0 has removed the dependency on JSON.NET and uses it’s own JSON serializer i.e ‘System.Text.Json‘.

ReferenceLoopHandling is currently not supported in the System.Text.Json serializer. This feature will be supported most probably .NET 5 version in the future.

Below was the codebase used which was producing the error for me and i was able to fix the issue using below measures,

I had Repository Pattern implemented with EFCore context,

public async Task<TEntity> Get(string id)
        {

            return await _context.Set<TEntity>().FindAsync(id.ToString());
        }

I was able to fix the issue adding the reference to NewtonsoftJson Nuget package,

PM> Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.2

And update the Startup.cs as below,

A possible object cycle was detected

Similarly, if you have IRouter based routing enabled for API (While migrating .NET Core 2.2 to 3.* version) using EnableEndpointRouting set as false you will get the same error.

Please try using below logic to fix the issue,

A possible object cycle was detected

References:

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.