JsonException object cycle 🟪 .NET

JsonException: A possible object cycle was detected

System.Text.Json found a reference loop (e.g. Order → Customer → Orders → …) while serialising, usually from EF Core navigation properties.

Seen on: .NET

Meaning

Returning EF entities directly from APIs serialises navigation properties in both directions, creating cycles (or depth > 64).

Common causes

  • Returning EF Core entities with bidirectional navigation properties
  • Include() loading both sides of a relationship
  • Self-referencing hierarchies (parent/children)

⚡ Quick fix

  1. Return DTOs/records with only the fields the client needs
  2. Or configure ReferenceHandler.IgnoreCycles
  3. Avoid Include() of back-references

Detailed fix by platform

.NET

  1. Ignore cycles globally (quick fix):
    csharp
    builder.Services.AddControllers().AddJsonOptions(o =>
        o.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles);

Code examples

Better: project to a DTO

csharp
var orders = await db.Orders
    .Select(o => new OrderDto(o.Id, o.Total, o.Customer.Name))
    .ToListAsync();

How to diagnose

  1. Type — Which entity graph is serialised?
  2. Navigation — Which properties point back?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.