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

Dung Do Tien Dec 28 2020 551

When loading a list of entities in ASP.NET core 3.1. Have got an exception 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.

I want to show a part of my project related to this issue bellow

Entity Model and DbContext :

public class Category
{
  public int Id { get; set; }
  public string Name { get; set; }
  public virtual IEnumerable<Product> Products { get; set; }
}

public class Product
{
  public int Id { get; set; }
  public string Name { get; set; }
  public virtual Category Category { get; set; }
}

public class MyDbContext : DbContext
{
  public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
  {

  }
        
   public DbSet<Category> Categories { get; set; }
   public DbSet<Product> Products { get; set; }
}

Here is Controller

public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
   return await _context.Products.Include(t=>t.Category).ToListAsync();
}
Have 1 answer(s) found.
  • S

    Sandeep Kumar Dec 28 2020

    I got the same issue. So, this is one solution for you

    Firstly, Add Nuget package Microsoft.AspNetCore.Mvc.NewtonsoftJson to parsing json instead of use default parsing.

    Afterthat, use AddNewtonsoftJson right after AddController (ControllerWithViews,Mvc also) in Startup.cs

    services.AddControllers().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });

    I hope it helps you resolve this issue

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close