Reputation: 21
I have 2 codes:
1st code:
public class CategoryController : ApiController
{
Shop_DTBEntities shop_DTBEntities = new Shop_DTBEntities();
public IEnumerable<Category> GetAll_Category()
{
return shop_DTBEntities.Categories.ToList<Category>();
}
}
When I run above code, it throw 1 error The 'ObjectContent
1` type failed to serialize the response body for content type 'application/json; charset=utf-8'."
After that, I add new 2 line code follow in global.asax is fixed:
protected void Application_Start()
{
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
But if the appli procedure with the 2nd code, then throw to error as above
2nd Code:
public IEnumerable<Category> GetAll_Category()
{
using (Shop_DTBEntities shop_DTBEntities = new Shop_DTBEntities())
{
return shop_DTBEntities.Categories.ToList<Category>();
}
}
Upvotes: 1
Views: 399
Reputation: 2442
You can fix it by one config settings.
Better to use it in the dbcontext constructor
public DbContext() // dbcontext constructor
: base("name=ConnectionStringNameFromWebConfig")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
Upvotes: 2