Fix “A Circular Reference Was Detected” When Returning JSON in ASP.NET MVC 5
Quick fix. Return a JSON response model with the fields the client needs. Serializing an entire EF entity with navigation properties can walk from a parent to its children and back to the same parent.
This guide applies to ASP.NET MVC 5 on .NET Framework (System.Web.Mvc).
Recognize the object graph
The query can complete successfully while the request still fails. MVC writes the JsonResult after the action returns. A category holding products, where each product has a Category property, forms a back-reference. EF proxies and lazy loading can make the graph larger, but a circle can exist even in plain, manually constructed objects.
Project only the public response fields
This example exposes a public category catalog. Replace the context and property names with those in your application. A database projection selects explicit fields before materialization. The JSON shape cannot traverse the original entity graph because the resulting objects have no reference back to the EF entities.
[HttpGet]
public ActionResult BrowseCategories()
{
var items = db.Categories
.Where(c => c.IsPublished)
.OrderBy(c => c.Name)
.ThenBy(c => c.Id)
.Take(50)
.Select(c => new
{
c.Id,
c.Name,
ProductCount = c.Products.Count(p => p.IsPublished)
})
.ToList();
return Json(new { items }, JsonRequestBehavior.AllowGet);
}
Preserve a deliberate API contract
The example uses AllowGet for public, read-only values. For private records, keep the endpoint’s existing access controls and review whether GET is appropriate for that response. If consumers need products, create a bounded list with selected product fields and omit its parent navigation. Raising the JSON length limit or suppressing all reference loops does not define what the client should receive.
Verify the serialized response
Call the route and inspect the response body as well as the status. Test a category with products and an empty category. Confirm the response includes the ID, name, and count for each expected row and excludes internal columns and navigation properties. For an existing API, check field names against a saved sample response before deploying.
Comments
Post a Comment