Asp.net mvc 4 ASP.NET Web Api System.Runtime.Serialization.SerializationException

Asp.net mvc 4 ASP.NET Web Api System.Runtime.Serialization.SerializationException,asp.net-mvc-4,xml-serialization,asp.net-web-api,Asp.net Mvc 4,Xml Serialization,Asp.net Web Api,我有一个完全可以工作的MVC4网站,今天我试图添加一个web API,但没有成功 <Error> <Message>An error has occurred.</Message> <ExceptionMessage> The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

我有一个完全可以工作的MVC4网站,今天我试图添加一个web API,但没有成功

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'System.Data.Entity.Infrastructure.DbQuery`1[[LeasingWeb.Models.Car, LeasingWeb, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfCar:http://schemas.datacontract.org/2004/07/LeasingWeb.Models' is not expected. Consider using a DataContractResolver 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 DataContractSerializer.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
<StackTrace>
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle) at WriteCarDBToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract ) at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass7.<WriteToStreamAsync>b__6() at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
</StackTrace>
</InnerException>
</Error>
以及一个能同时容纳这两个物体的物体:

public class CarDB
{
    public IQueryable<Car> Cars { get; set; }
    public IEnumerable<Image> Images { get; set; }
}

感谢所有能够提供帮助的人。

这里的问题是CarDB对象上的Cars成员。DataContractSerializer的特殊情况集合接口,如IEnumerable和IList,但它没有特殊情况派生接口,如IQueryable。对于这些接口,它们被视为类型是对象,任何实现都必须声明为已知类型


您可以尝试通过将IQueryable成员更改为IEnumerable来解决此问题。

这里的问题是CarDB对象上的Cars成员。DataContractSerializer的特殊情况集合接口,如IEnumerable和IList,但它没有特殊情况派生接口,如IQueryable。对于这些接口,它们被视为类型是对象,任何实现都必须声明为已知类型


您可以尝试通过将IQueryable成员更改为IEnumerable来修复此问题。

我在使用30个表和大约40个外键以及延迟加载的遗留代码时遇到了此问题。我发现只创建一个包含我想要返回的字段的ViewModel比向所有数据库类添加更多注释更容易。
如果返回的数据很复杂,那么我建议使用automapper

我在使用30个表和大约40个外键以及延迟加载的遗留代码时遇到了这个问题。我发现只创建一个包含我想要返回的字段的ViewModel比向所有数据库类添加更多注释更容易。
如果返回的数据很复杂,那么我建议使用automapper

我需要为[KnownType]添加什么参考资料?找不到类型或命名空间名称“KnownTypeAttribute”是否缺少using指令或程序集引用?System.Runtime.Serialization我觉得有点愚蠢,但我仍然无法让它接受[KnownType]属性,即使使用该引用,它也不承认这是一个有效的命令。如果它只是一个使用标签,VS2012会自动提供它,这很奇怪。确保有对System.Runtime.Serialization的引用,并尝试使用System.Runtime.Serialization添加;看看这是否有帮助。如果您不关心返回XML,那就很好了。JSON是WebApi的默认格式。尽管您甚至不应该需要PreserveObjectReferences,除非您的对象图中有循环。我需要为[KnownType]添加什么引用?找不到类型或命名空间名称“KnownTypeAttribute”是否缺少using指令或程序集引用?System.Runtime.Serialization我觉得有点愚蠢,但我仍然无法让它接受[KnownType]属性,即使使用该引用,它也不承认这是一个有效的命令。如果它只是一个使用标签,VS2012会自动提供它,这很奇怪。确保有对System.Runtime.Serialization的引用,并尝试使用System.Runtime.Serialization添加;看看这是否有帮助。如果您不关心返回XML,那就很好了。JSON是WebApi的默认格式。尽管您甚至不应该需要PreserveObjectReferences,除非您的对象图中有循环。
public class CarDB
{
    public IQueryable<Car> Cars { get; set; }
    public IEnumerable<Image> Images { get; set; }
}
public CarDB Get(int ID = -1)
{
    CarDB car = new CarDB();
    if (ID == -1)
    {
        car = new CarDB { Cars = db.Cars.Include(c => c.CarType), Images = db.Images };
    }
    else
    {
        car = new CarDB { Cars = db.Cars.Where(c => c.ID == ID).Include(c => c.CarType), Images = db.Images.Where(c => c.CarID == ID) };
    }
    return car;
}