【问题标题】:Customizing XmlSerialization in WCF?在 WCF 中自定义 XmlSerialization?
【发布时间】:2013-09-16 14:44:14
【问题描述】:

在 WCF 服务中,目前无法迁移到 DataContract Serialization。我需要控制 xml 序列化默认行为。

这是我的 POCO 类,我需要在这些类上完全控制序列化过程。

[Serializable]
public class ProductBase
{
    public int Id { get; set; }
}

[Serializable]
public class DurableProduct : ProductBase
{
    public string Name { get; set; }
    public Price Pricing { get; set; }
}

[Serializable]
public class Price : IXmlSerializable
{
    public int Monthly { get; set; }
    public int Annual { get; set; }
}

我需要控制DurableProductPrice 类的序列化过程。因此,我在这些类上实现了IXmlSerializable,如下所示-

[Serializable]
public class DurableProduct : ProductBase, IXmlSerializable
{
    public string Name { get; set; }
    public Price Pricing { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        Id = int.Parse(reader.ReadElementString());
        Name = reader.ReadElementString();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteElementString("Id", Id.ToString());
        writer.WriteElementString("Name", Name);
    }

    public override string ToString()
    {
        return string.Format("Id : {0}, Name: {1}, Monthly: {2}", Id, Name, Pricing.Monthly);
    }
}

[Serializable]
public class Price : IXmlSerializable
{
    public int Monthly { get; set; }
    public int Annual { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        //Control never reaches here, while deserializing DurableProduct
        Monthly = int.Parse(reader.ReadElementString());
        Annual = int.Parse(reader.ReadElementString());
    }

    public void WriteXml(XmlWriter writer)
    {
        //Control never reaches here, while deserializing DurableProduct
        writer.WriteElementString("MyCustomElement1", Monthly.ToString());
        writer.WriteElementString("MyCustomElement2", Annual.ToString());
    }
}

问题当我尝试序列化/反序列化时,没有调用 IXmlSerializable => ReadXml / WriteXml 类。

如何实现我的类,以便所有读/写 IXmlSerializable 的实现被可靠地调用。

【问题讨论】:

    标签: c# wcf serialization


    【解决方案1】:

    您可以尝试使用这些属性来装饰您的操作合同:

    [OperationContract(Action = "urn:yourActionNamesapce", ReplyAction = "urn:yourReplyActionNamesapce")]
    [XmlSerializerFormat()]
    [ServiceKnownType(typeof(ProductBase))]
    [ServiceKnownType(typeof(DurableProduct))]
    [ServiceKnownType(typeof(Price))]
    YourResponse YourOperation(DurableProduct request);
    

    然后,您只需在调用 Web 服务时将 POCO 传递给客户端。

    DurableProduct request = ...
    using (YourClient client = new YourClient())
    {
        client.YourOperation(request);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      相关资源
      最近更新 更多