0

在 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 的所有读/写实现。

4

1 回答 1

0

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

[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);
}
于 2013-09-16T16:06:35.147 回答