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>();
    }
}
2

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.