The Error
API returns 500:
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.
Quick Fix - 30 Seconds
Your EF entities reference each other. User → Orders → User → Orders... Add this to Program.cs:
builder.Services.Configure<JsonOptions>(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
Why This Happens
EF Core creates navigation properties. User.Orders and Order.User point to each other. JSON serializer tries to follow them forever and crashes.
Best Practice for.NET 8
1. Use DTOs: Never return EF entities directly. Map to UserDto with no cycles
2. IgnoreCycles: Quick fix above. Safe for APIs
3. JsonIgnore: Add [JsonIgnore] to Order.User to break the loop
No comments yet. Be the first to share your thoughts!