C# – failed to serialize the response in Web API

asp.net-web-apicserialization

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?

Best Answer

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.