Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

failed to serialize the response in Web API

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?

like image 468
Tamal kanti Dey Avatar asked Sep 28 '12 13:09

Tamal kanti Dey


2 Answers

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.

like image 66
Zane Avatar answered Oct 26 '22 01:10

Zane


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!

like image 38
Julito Avellaneda Avatar answered Oct 26 '22 01:10

Julito Avellaneda