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?
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With