dotnet / dotnet/aspnetcore

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

Open
#63,857 8 comments 7 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [x] 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`

```csharp

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

[HttpGet("test-issue")]
public ActionResult 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 Orders { get; set; } = [];
public ICollection Products { get; set; } = [];
public ICollection Courses { get; set; } = [];
public ICollection Cars { get; set; } = [];
public ICollection Hourses { get; set; } = [];
public ICollection Plans { get; set; } = [];
public ICollection Rights { get; set; } = [];
public ICollection 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:

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

### Steps To Reproduce

**I have provided a reproducible sample code repository**

[The Issue example](https://github.com/niltor/IssueSample/tree/main/OpenApiIssue)

### 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_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.