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

时间:2013-03-18 16:52:06

标签: asp.net xml-serialization asp.net-web-api

我正在使用.net WebApi来创建Web服务,并且当其中一个属性是派生类的IEnumerable时,我遇到了将类序列化为XML的问题。我尝试添加knownType下注得到错误:

  

“错误1属性'KnownType'在此声明类型上无效。   它仅对'class,struct'声明有效。“

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>
....

派生类示例

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
}

Class to serialzie

public class order
{
    public int orderNumber{ get; set; }
    //..... more
    public IEnumerable<orderDetailBase> { get; set; }   // Serializing this causes issues

如何解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试修改'orderDetailBase'类,如下所示:

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