ASP.NET WEB API: Error Self referencing loop detected for type

Updated on     Kisan Patel

Problem:

JSON.NET Error Self referencing loop detected for type

How to solve self referencing loop issue when using Newtonsoft.Json

The “Self referencing loop detected” error is thrown when transferring server data to the client side

Solution:

The json.net serializer has an option to ignore circular references. Put the following code in WebApiConfig.cs file:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.Remove(config.Formatters.XmlFormatter);

Preserving circular reference globally

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.Remove(config.Formatters.XmlFormatter);

ASP.NET MVC

Leave a Reply