1

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 'ObjectContent1` 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>();
    }
}
Kahbazi
  • 14,331
  • 3
  • 45
  • 76

1 Answers1

2

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;
}
Md. Alim Ul Karim
  • 2,401
  • 2
  • 27
  • 36