86

I was working on ASP.NET MVC web API, I'm having this error:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

My controller is:

public Employee GetEmployees() { Employee employees = db.Employees.First(); return employees; } 

why I m getting this error?

4
  • 6
    The exception you are seeing is a general exception, which can be caused by any number of factors. Check the InnerException property of the serialization exception to find out what exactly caused the serialization to fail. Commented Sep 28, 2012 at 14:35
  • Can you share the code for your Employee type? It might be because the type Employee is not serializable... Commented Oct 4, 2012 at 3:07
  • Also have a look at this stackoverflow.com/questions/8173524/… Commented Jun 4, 2013 at 19:40
  • Possible duplicate of JSON.NET Error Self referencing loop detected for type Commented Oct 31, 2017 at 20:38

15 Answers 15

121

For me this was a problem with circular referencing.

The accepted answer did not work for me because it only changes the behaviour of the JSON formatter, but I was getting XML when I called the service from the browser.

To fix this, I switched off XML and forced only JSON to be returned.

In the Global.asax file, put the following lines at the top of your Application_Start method:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); 

Now only JSON results will be returned. If you need XML results, you will need to find a different solution.

Sign up to request clarification or add additional context in comments.

4 Comments

worked for me.but the thing is i am using POSTMAN. it's a chrome extension. when i post data with POSTMAN it works fine. but when i use restsharp it gives me this error. anyway your solution fixed my problem
This answer does not provide a solution to use xml, and that is what he asked for.
Works for me as i switched on to json from xml.
Actually, this answer gets to the root of the problem. The first error I received was a circular reference error (trying to return JSON from MVC controller). When I switched to an API inherited controller, I started to get this error instead. When I added the code above to Global.asax the error went away.
43

in your global.asax file, in the Application_start() method add this line:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

I hope that helps you!

5 Comments

What is application_start and where can it be found? And where exactly should this line be placed?
Sorry but what is the meaning of this statement?
Line added to Global.asax's Application_Start, but no change.
This still didn't work for me. However I added another line after the one in this answer and it worked: GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); I have created a more full answer below
This answer should not be accepted because it indeed removes XmlSerializer rather than addressing the problem of circular reference with XmlSerializer.
29

I got the same problem. And I solved it. I put the default constructor to the DTO class.

Ex:

public class User { public User() { } } 

Hope it work with you!

3 Comments

Thanks for the suggestion, this helped me with the xml response, but does anyone know why it needs a default constructor? We have the data already...
I think when an object is serialized from response, first the constructor was called to create instance of object, after that, set method is used to set data to object instance. That's my guess.
This should actually be the chosen answer as it doesn't make any assumption about the return types you need. This will work for both XML and JSON. Thanks for posting this.
22

Put this in constructor. Hope this solve the problem:

 public MyController() { db.Configuration.ProxyCreationEnabled = false; } 

3 Comments

Excellent solution. I need to put it into the constructor and it worked.
This worked for me in combination with the GlobalConfiguration settings. But why does this work? Any explanation as to how this fixes the problem? And what the problem actually was?
To understand what entity proxies are: msdn.microsoft.com/en-us/library/jj592886(v=vs.113).aspx To understand what ProxyCreationEnabled is: stackoverflow.com/questions/7111109/…
16

I found two solutions to this. The first and easiest to implement is to change any IEnumerables, ICollections to a type of List. The WebAPI can serialize this objects, it however cannot serialize interface types.

public class Store { [StringLength(5)] public string Zip5 { get; set; } public virtual List<StoreReport> StoreReports { get; set; } //use a list here } 

The other option is to not use the native JSON serializer and run this override in the Register method of the WebApi Config:

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

1 Comment

While changing to List worked for me adding a parameterless constructor also worked for me and I could continue to return IEnumerable<Widget>
8

Solution is simple.

After LINQ query add .ToList() (or ToDictionary if need).

It will do eager loading than lazy loading of the data

1 Comment

Changing the action return type to IENumerable and adding .TiList() to the return worked for me.
5

** this bug occur when calling from request web api/wcf/... from client side, but as side effect, you will need to include depending relations by include keyword. **

public CustomerPortalContext() : base("Name=CustomerPortalContext") { base.Configuration.ProxyCreationEnabled = false; } 

Comments

4

If you are working with EF, besides adding the code below on Global.asax

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); 

Dont`t forget to import

using System.Data.Entity; 

Then you can return your own EF Models

Comments

3

please check the web api documentation for this problem, Handling Circular Object References

Regards

Comments

3

If you use web api with Entity Framework, a solution can be Failed to serialize the response in Web API with Json

Basically, you need to create a model corresponding to each EF model, this removes dependencies between classes and allow easy serialization.

Code: (taken from the referenced link)

Create a UserModel

public class UserModel { public string FirstName { get; set; } public string LastName { get; set; } } 

Change my method GetAll()

public IEnumerable<UserModel> GetAll() { using (Database db = new Database ()) { List<UserModel> listOfUsers = new List<UserModel>(); UserModel userModel = new UserModel(); foreach(var user in db.Users) { userModel.FirstName = user.FirstName; userModel.LastName = user.LastName; listOfUsers.Add(userModel); } IEnumerable<UserModel> users = listOfUsers; return users; } } 

Comments

2

Default Entity 6 use XML to apis, in your project, find the file "Global.asax" File and add this line:

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); 

This line remove the XML Formatter.

1 Comment

Hello, Web API serialize the response in XML and JSON, if you add header Content-Type : application/json, the response is in JSON, you need define this header, in the browser always you can see it as XML format
1

but if you found this problem with other entities/classes, you have to create a new DTO for each class, and if you have a lot of them, you can find a problem, also I think that create a DTO only for solving this problem is no the best way...

Did you try this?

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All; 

Regards

Comments

1

hmmm, Following may help.

I was getting the same exception, and in my case I was passing the actual poco entity created for entity code first. Since, it contains relation with other entities, I just created the viewmapper/dto entity on top of it to return.

It works fine now.

Poco Entity:

public class Tag { public int Id{get;set;} public string Title{get;set;} public IList<Location> Locations{get;set;} } 

ViewMapper/Dto

public class TagResultsViewMapper { public int Id{get;set;} public string Title{get;set;} //just remove the following relationship //public IList<Location> Locations{get;set;} } 

Comments

0

Your question is quite similar to mine. You must not return data from database directly. For this, you must create Model and associate data you want show.

In my example, There are data about User that Json couldn't serialize, I had create a userModel and, in my API, I return userModel instead User from database.

The logic of convert or associate data between User and UserModel must be in API.

Failed to serialize the response in Web API with Json

Comments

0

This was the specific error I was getting back from my odata Web API call:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'. 

I finally figured out that my dbContext class had a poorly formatted table name being assigned in onModelCreating.. so the SqlClient was dying looking for a table that didn't exist in my db!!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.