Skip to content

The depth of the generated JSON schema exceeds the JsonSerializerOptions.MaxDepth setting #63857

@niltor

Description

@niltor

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

After some investigation, I provided the simplest reproducible content possible, a new asp.net core project, a simple api, and some class models.

When a class, such as User in the example, has more than or equal to 8 relate classes, an error of The depth of the generated JSON schema exceeds the JsonSerializerOptions.MaxDepth setting will be reported. When there are less than 8, no error will be reported.

IssueController.cs

[ApiController]
[Route("[controller]")]
public class IssueController : ControllerBase
{

    [HttpGet("test-issue")]
    public ActionResult<User> TestIssue()
    {
        var user = new User() { Name = "User" };
        return user;
    }
}

public class User
{
    public Guid Id { get; set; }
    public required string Name { get; set; }
    public ICollection<Order> Orders { get; set; } = [];
    public ICollection<Product> Products { get; set; } = [];
    public ICollection<Course> Courses { get; set; } = [];
    public ICollection<Car> Cars { get; set; } = [];
    public ICollection<Hourse> Hourses { get; set; } = [];
    public ICollection<Plan> Plans { get; set; } = [];
    public ICollection<Right> Rights { get; set; } = [];
    public ICollection<Salary> Salarys { get; set; } = [];
}

public class Order { public User? User { get; set; } }
public class Product { public User? User { get; set; } }
public class Course { public User? User { get; set; } }
public class Car { public User? User { get; set; } }
public class Hourse { public User? User { get; set; } }
public class Plan { public User? User { get; set; } }
public class Right { public User? User { get; set; } }
public class Salary { public User? User { get; set; } }

In actual projects, there are more than 8 related entities like User, and dozens of them are possible.

Expected Behavior

Swashbuckle will not throw this exception.

Maybe support Json config like:

builder.Services.AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});

Steps To Reproduce

I have provided a reproducible sample code repository

The Issue example

Exceptions (if any)

got error: The depth of the generated JSON schema exceeds the JsonSerializerOptions.MaxDepth setting

.NET Version

.NET9 and .NET 10

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions