I'm aware that question is quite old, but it's still popular and I can't see any solution for ASP.net Core.
I case of ASP.net Core, you need to add new JsonOutputFormatter
in Startup.cs
file:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.OutputFormatters.Clear();
options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
}, ArrayPool<char>.Shared));
});
//...
}
After implementing it, JSON serializer will simply ignore loop references. What it means is: it will return null instead of infinitely loading objects referencing each other.
Without above solution using:
var employees = db.Employees.ToList();
Would load Employees
and related to them Departments
.
After setting ReferenceLoopHandling
to Ignore
, Departments
will be set to null unless you include it in your query:
var employees = db.Employees.Include(e => e.Department);
Also, keep in mind that it will clear all OutputFormatters, if you don't want that you can try removing this line:
options.OutputFormatters.Clear();
But removing it causes again self referencing loop
exception in my case for some reason.