I am working with ASP.NET MVC 5 Web Api. I want consult all my users.
I wrote api/users
and I receive this:
"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'"
In WebApiConfig, already I added these lines:
HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
But it still doesn't work.
My function for return data is this:
public IEnumerable<User> GetAll()
{
using (Database db = new Database())
{
return db.Users.ToList();
}
}
I don't like this code:
foreach(var user in db.Users)
As an alternative, one might do something like this, which worked for me:
However, I ended up using Lucas Roselli's solution.
Update: Simplified by returning an anonymous object:
My personal favorite: Just add the code below to
App_Start/WebApiConfig.cs
. This will return json instead of XML by default and also prevent the error you had. No need to editGlobal.asax
to removeXmlFormatter
etc.Another case where I received this error was when my database query returned a null value but my user/view model type was set as non-nullable. For example, changing my UserModel field from
int
toint?
resolved.If you are working with EF, besides adding the code below on Global.asax
Dont`t forget to import
Then you can return your own EF Models
Simple as that!
This also happens when the Response-Type is not public! I returned an internal class as I used Visual Studio to generate me the type.
Add this code to
global.asax
below onApplication_Start
:Update from
.Ignore
to.Serialize
. It must work.