Asp.net 如何在.net WebApi中序列化派生类的IEnumerable

Asp.net 如何在.net WebApi中序列化派生类的IEnumerable,asp.net,xml-serialization,asp.net-web-api,Asp.net,Xml Serialization,Asp.net Web Api,我正在使用.NETWebAPI创建一个web服务,当一个属性是派生类的IEnumerable时,将一个类序列化为XML会出现问题。我已尝试添加knownType赌注,但出现以下错误: “错误1属性“KnownType”对此声明类型无效。 它仅对“类,结构”声明有效。“ JSON序列化工作完美,但对于XML,我得到: <Error> <Message>An error has occurred.</Message> <ExceptionMessage>

我正在使用.NETWebAPI创建一个web服务,当一个属性是派生类的IEnumerable时,将一个类序列化为XML会出现问题。我已尝试添加knownType赌注,但出现以下错误:

“错误1属性“KnownType”对此声明类型无效。 它仅对“类,结构”声明有效。“

JSON序列化工作完美,但对于XML,我得到:

<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 'test.order' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
</ExceptionMessage>
....
将类转换为serialzie

public class orderDetailBase
{
    public int sequence { get; set; }
    //.... more properties
}

public class onlineOrderDetail : orderDetailBase
{
    public string ip { get; set; }
    //.... more properties
}

public class inStoreOrderDetail : orderDetailBase
{
    public string storeAddress { get; set; }
    //.... more properties
}
public class order
{
    public int orderNumber{ get; set; }
    //..... more
    public IEnumerable<orderDetailBase> { get; set; }   // Serializing this causes issues
公共类秩序
{
public int orderNumber{get;set;}
//……更多
public IEnumerable{get;set;}//序列化会导致问题

有什么办法可以解决这个问题吗?谢谢!

你能试着修改你的“orderDetailBase”类吗,如下所示:

[DataContract]
[KnownType(typeof(onlineOrderDetail))]
[KnownType(typeof(inStoreOrderDetail))]
public class orderDetailBase
{
   [DataMember]
   public int sequence { get; set; }

我在尝试时出错。基本上说knowtype只能用于类或结构。对IEnumerable不起作用。嗯…你是否在属性IEnumerable上应用KnownType属性?…如果是,请删除它,然后重试…你是对的,我在错误的位置使用了它。我现在可以看到xml,但我得到的不是以下数据:r我的4个细节我更新了我上面的帖子。由于类已经用datacontract属性修饰,我们需要用datamember属性修饰它(例如:上面的sequence属性)…不管属性“ip”是否应该序列化…您是否真的有“ip”属性,或者只是为了这篇论坛文章…谢谢,DataMember做到了!ip只是为了这篇文章:)