The 'ObjectContent`1' type failed to serialize the response body for content type in WebAPI [duplicate]

橙三吉。 提交于 2019-12-25 08:58:04

问题


I have an MVC5 app, and I have included WebAPI inside it. I tested it and it worked fine for simple string and stuff. Then I tried to do something like this:

public Business Get(string id)
{
     return db.Businesses.Where(b => b.Id == id).FirstOrDefault();
}

And I got the above mentioned error. Please note that Business is a custom type that I created in my models folder. In my WebApiConfig file I have something like this:

var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
formatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Any idea how to solve the problem?

EDIT:

Some more of the error message:

Type 'System.Data.Entity.DynamicProxies.Business_32C47B90BA261D075748CEC009DA52F8C6D893134F8D33848A7F856F76F50D55' with data contract name 'Business_32C47B90BA261D075748CEC009DA52F8C6D893134F8D33848A7F856F76F50D55:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.System.Runtime.Serialization.SerializationException


回答1:


I found the solution. I simply needed to include this line of code:

DbContext.Configuration.ProxyCreationEnabled = false;


来源:https://stackoverflow.com/questions/28150187/the-objectcontent1-type-failed-to-serialize-the-response-body-for-content-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!