在WCF服务中,目前无法迁移到DataContract Serialization
。我需要控制xml-serialization的默认行为。
以下是我的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; }
}
我需要控制类DurableProduct
,Price
的序列化过程。因此,我在这些类上实现了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的实现。
答案 0 :(得分: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);
}