'ObjectContent`1' 类型无法序列化 WebAPI 中内容类型的响应正文
The 'ObjectContent`1' type failed to serialize the response body for content type in WebAPI
我有一个 MVC5 应用程序,我在其中包含了 WebAPI。我测试了它,它适用于简单的字符串和东西。然后我尝试做这样的事情:
public Business Get(string id)
{
return db.Businesses.Where(b => b.Id == id).FirstOrDefault();
}
我遇到了上述错误。请注意,Business 是我在模型文件夹中创建的自定义类型。在我的 WebApiConfig
文件中,我有这样的内容:
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
formatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
知道如何解决这个问题吗?
编辑:
更多错误信息:
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
我找到了解决方案。我只需要包括这行代码:
DbContext.Configuration.ProxyCreationEnabled = false;
我有一个 MVC5 应用程序,我在其中包含了 WebAPI。我测试了它,它适用于简单的字符串和东西。然后我尝试做这样的事情:
public Business Get(string id)
{
return db.Businesses.Where(b => b.Id == id).FirstOrDefault();
}
我遇到了上述错误。请注意,Business 是我在模型文件夹中创建的自定义类型。在我的 WebApiConfig
文件中,我有这样的内容:
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
formatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
知道如何解决这个问题吗?
编辑:
更多错误信息:
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
我找到了解决方案。我只需要包括这行代码:
DbContext.Configuration.ProxyCreationEnabled = false;