Reputation: 89
I am working on an ASP.NET Web API simply trying to return some data from my database, but I keep getting this error:
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
I have tried adding the following to the Global.asax file as suggested in other questions similar to mine, but all it does is change the formatting of the error.
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
My controller looks like the following:
public class SQLController : ApiController
{
public IEnumerable<Alias> Get()
{
using (DatabaseEntities entities = new DatabaseEntities())
{
return entities.Aliases.ToList();
}
}
public Alias Get(int id)
{
using (DatabaseEntities entities = new DatabaseEntities())
{
return entities.Aliases.FirstOrDefault(a => a.ID == id);
}
}
}
I tried something very similar with a much simpler database and it worked fine. I have also read that making a separate data model could fix this issue? if so why, and how would I go about doing that? Any help with figuring out why I am receiving this error would be appreciated.
Upvotes: 0
Views: 770
Reputation: 1
Try This
Use "IHttpActionResult" for the return type
[HttpGet]
public IHttpActionResult Get()
{
using (DatabaseEntities entities = new DatabaseEntities())
{
return Ok(entities.Aliases.ToList());
}
}
public IHttpActionResult Get(int id)
{
using (DatabaseEntities entities = new DatabaseEntities())
{
return Ok(entities.Aliases.FirstOrDefault(a => a.ID == id));
}
}
Upvotes: 0
Reputation:
Looks like a problem with entity framework lazy loading related entities and creating an endless loop.
Your best bet would be to disable lazy loading and manually loading related objects. Lazy loading can be disabled globally for the entire Context, only for some relations or even locally per query.
Globaly:
public class BloggingContext : DbContext
{
public BloggingContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}
Locally:
using (DatabaseEntities entities = new DatabaseEntities())
{
entities.Configuration.LazyLoadingEnabled = false;
return entities.Aliases.FirstOrDefault(a => a.ID == id);
}
If you want to disable for a specific property, you should just remove virtual from the navigation property:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Tags { get; set; }
public ICollection<Post> Posts { get; set; }
}
For more data about this refer to the offical micrsofot documentation https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx
Upvotes: 1