System.Text.Json: A possible object cycle was detected
Serialization hit a cycle or the depth limit: EF navigation properties point both ways. Project a DTO, use IgnoreCycles, or Preserve references.

Introduction & Quick Summary
System.Text.Json.JsonException: A possible object cycle was detected.
This can either be due to a cycle or if the object depth is larger than the
maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on
JsonSerializerOptions to support cycles.
Path: $.orders[0].customer.orders[0].customer.orders ...System.Text.Json refuses to serialize an object graph it cannot finish. A cycle — parent pointing at child, child pointing back at parent — would produce infinite JSON, so the serializer stops at 64 levels and throws. EF Core navigation properties create exactly this shape by default.
Four fixes, from best to last resort:
- Project to a DTO. Serialize a shape that has no back-references. This also fixes over-posting and oversized payloads.
ReferenceHandler.IgnoreCycles. The serializer writesnullwhere the cycle would repeat, so the JSON stays finite and deserializes without metadata.ReferenceHandler.Preserve. Emits$idand$refentries so the graph round-trips. Only use it when the client understands that contract.[JsonIgnore]on the back-pointer. Keeps the graph intact for code, removes one direction for JSON.
If the graph is genuinely deep rather than cyclic, the depth limit is the problem and MaxDepth is the setting — but a 64-level business object usually means an accidental recursion, not a legitimate one.
| Approach | Output shape | Round-trips graph | Client impact |
|---|---|---|---|
| DTO projection | Flat, explicit | No | Clean, stable contract |
IgnoreCycles | Cycle becomes null | No | May see unexpected nulls |
Preserve | $id / $ref | Yes | Requires matching serializer |
[JsonIgnore] | One direction removed | No | Smaller payload |
MaxDepth raised | Full repetition | No | Huge payloads, still finite |
Core Mechanics, Signatures & Reproducible Setup
JsonSerializer walks the object graph depth-first and tracks how deep it currently is. When depth exceeds MaxDepth (64 by default) it throws JsonException with the cycle hint, because the two conditions are indistinguishable from the writer's perspective without reference tracking.
Reproduction with plain classes:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = "";
public List<Order> Orders { get; set; } = new();
}
public class Order
{
public int Id { get; set; }
public Customer Customer { get; set; } = null!;
public List<OrderLine> Lines { get; set; } = new();
}
public class OrderLine
{
public int Id { get; set; }
public Order Order { get; set; } = null!;
public int Quantity { get; set; }
}var customer = new Customer { Id = 1, Name = "Ada" };
var order = new Order { Id = 10, Customer = customer };
customer.Orders.Add(order);
order.Lines.Add(new OrderLine { Id = 100, Order = order, Quantity = 2 });
var json = JsonSerializer.Serialize(customer);
// JsonException: A possible object cycle was detected.EF Core produces the same structure from Include calls, because navigation fixup sets both sides of every relationship.
The minimal options-based fix:
var options = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.IgnoreCycles,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = false
};
var json = JsonSerializer.Serialize(customer, options);IgnoreCycles replaces the repeated reference with null; WhenWritingNull then drops those properties, which keeps the payload readable.
Key Comparison Table
| Option | Where to set | Applies to |
|---|---|---|
ReferenceHandler.IgnoreCycles | JsonSerializerOptions | JsonSerializer, MVC, minimal APIs |
ReferenceHandler.Preserve | JsonSerializerOptions | Requires Preserve on read |
MaxDepth | JsonSerializerOptions | Any graph, cycle or not |
[JsonIgnore] | Property or field | All serialization of that type |
| DTO / projection | Query or mapping layer | Preferred for APIs |
ReferenceLoopHandling.Ignore | Newtonsoft.Json settings | Newtonsoft only |
| Serializer | Default cycle behavior | Fix |
|---|---|---|
| System.Text.Json (ASP.NET Core 3.0+) | Throws | Handler or DTO |
| Newtonsoft.Json (ASP.NET Core 2.x default) | Serializes until stack limit | ReferenceLoopHandling.Ignore |
JsonSerializer with source generation | Same as reflection path | Handler supported |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: Project before serializing
[HttpGet("customers/{id:int}")]
public async Task<ActionResult<CustomerDto>> Get(int id)
{
var customer = await db.Customers
.Include(c => c.Orders)
.ThenInclude(o => o.Lines)
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == id);
if (customer is null) return NotFound();
return new CustomerDto(
customer.Id,
customer.Name,
customer.Orders.Select(o => new OrderDto(
o.Id,
o.Lines.Select(l => new LineDto(l.Id, l.Quantity)).ToList()
)).ToList());
}public record LineDto(int Id, int Quantity);
public record OrderDto(int Id, List<LineDto> Lines);
public record CustomerDto(int Id, string Name, List<OrderDto> Orders);The DTO has no reference to its parent, so no cycle exists. It also stops the API from silently exposing new entity properties added later — a serializer setting cannot do that.
Case 2: IgnoreCycles and the null it writes
builder.Services.ConfigureHttpJsonOptions(o =>
{
o.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
o.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});For minimal APIs, ConfigureHttpJsonOptions is the hook; AddControllers().AddJsonOptions(...) only affects MVC. Setting one and testing the other is a common reason "the fix did nothing".
With IgnoreCycles, the second occurrence of a reference becomes null — not omitted unless WhenWritingNull is set, and not merged. A client that expects customer.orders[0].customer.name gets null there. That may be acceptable for a detail endpoint and unacceptable for an export.
Case 3: Preserve changes the contract
o.SerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;{
"$id": "1",
"Id": 1,
"Name": "Ada",
"Orders": {
"$id": "2",
"$values": [
{
"$id": "3",
"Id": 10,
"Customer": { "$ref": "2" },
"Lines": { "$values": [] }
}
]
}
}Every object becomes an $id-tagged node and arrays gain a $values wrapper.
Case 4: [JsonIgnore] on one side
public class Order
{
public int Id { get; set; }
public List<OrderLine> Lines { get; set; } = new();
[JsonIgnore]
public Customer Customer { get; set; } = null!;
}This removes the back-pointer from every serialization of Order, including nested ones, and does not affect EF Core mapping. It is the cheapest fix when the entity must be serialized directly, and it fails quietly if a client needs that field — a serializer-level decision embedded in a domain model.
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] does not help: the back-pointer is not null, it points at a live object.
Case 5: Depth, not a cycle
public class Node
{
public string Name { get; set; } = "";
public List<Node> Children { get; set; } = new();
}A 70-deep category tree trips the same exception with a legitimate structure. Raising the limit is correct here:
var options = new JsonSerializerOptions { MaxDepth = 128 };Raise it deliberately and keep serialization bounded.
Case 6: The Newtonsoft escape hatch does not exist here
// Newtonsoft
JsonConvert.SerializeObject(value, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});Projects migrating from Newtonsoft often copy the setting and expect the same behavior from System.Text.Json, which has no ReferenceLoopHandling. The nearest equivalents are ReferenceHandler.IgnoreCycles (write null) and Preserve (write $ref); Newtonsoft's Ignore silently omits the property instead of writing null, which is why payloads can change shape during the migration.
Common Compilation/Runtime Mistakes & Version Gotchas
- Setting options on the wrong serializer.
JsonUtils.Optionsused directly,AddJsonOptionsapplied to a minimal API, orJsonSerializerOptions.Defaultmutated at runtime — all leave the HTTP pipeline on its own defaults. IgnoreCycleswithoutWhenWritingNull. The payload grows with"customer": nullentries that clients must tolerate.Preserveon one side only. A service that writes$idand a consumer that reads a normal DTO getnulls or deserialization errors with no obvious cause.AsNoTrackingdoes not remove fixup. The entities still reference each other; tracking only changes whether changes are saved.- Source-generated contexts.
JsonSerializerContextsupportsReferenceHandler, but options must be attached to the context, not passed per call. - Entity Framework lazy loading proxies. Lazy loading can create cycles that do not exist in the mapped model;
Include/projection removes the surprise. - .NET version drift. Cycle messages and
Path:detail differ between .NET 6 and 8/9, andPathis the fastest way to find the offending navigation property.
Paste a failing payload into the JSON formatter to see how deep the repetition goes before it becomes null, and use the diff tool to compare a working DTO response with the entity response that broke — the extra back-reference is usually one line.
Primary references: Preserve references in System.Text.Json documents ReferenceHandler.IgnoreCycles and Preserve, and the System.Text.Json overview covers MaxDepth, options and source generation.
Official references
primary documentationThe C# documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC#: NullReferenceException: Object reference not set
The message never names the null. Read the stack trace, enable nullable reference types, and use null-conditional access instead of guessing.
C# CS7036: no argument given that corresponds to the required parameter
CS7036 means the chosen constructor or method expects an argument the caller skipped. Match the signature instead of casting or adding a null default.
C# CS0117: 'X' does not contain a definition for 'Y'
CS0117 means the compiled assembly has no such member, usually from an older target framework or package. Check the API surface before editing code.
C# CS0246: The type or namespace name could not be found
CS0246 is a compile-time resolution failure: a missing using, package, target framework, or an unrestored project. Trace it backward from the symbol.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.