WCF运用XML序列化接口通讯
最近客户那里提出要用RESTful服务,并且指明要用标准的XML形式进行数据传输。
那么在WCF这个开发平台下,如何实现呢?WCF默认采用DataContract形式序列化,即不管你的服务接口上有没有使用DataContract序列化属性,WCF都是使用这个序列化属性的。如果想使用XML形式序列化。那么就要在服务接口上添加[XmlSerializerFormat]这个属性。例如以下代码:
// 注意: 如果更改此处的接口名称 "IService1",也必须更新 Web.config 中对 "IService1" 的引用。
[ServiceContract]
[XmlSerializerFormat]
public interface IVisitCostService
{
}
[ServiceContract]
[XmlSerializerFormat]
public interface IVisitCostService
{
}
另外,在你的数据契约上也要添加[Serializable]属性,并且相关字段也要有[XmlArray]、[XmlArrayItem]属性。例如以下代码:
[Serializable]
[XmlType(AnonymousType = false)]
[XmlRoot(Namespace = "", IsNullable = false)]
public class VisitCostRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="VisitCostRequest"/> class.
/// </summary>
public VisitCostRequest()
{
CountryCodes = new Collection<string>();
}
/// <summary>
/// Gets or sets the Countries list
/// </summary>
[XmlArray("Country")]
[XmlArrayItem("Code")]
//[DataMember(Name = "CountryCodes")]
public Collection<string> CountryCodes { get; set; }
}
[XmlType(AnonymousType = false)]
[XmlRoot(Namespace = "", IsNullable = false)]
public class VisitCostRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="VisitCostRequest"/> class.
/// </summary>
public VisitCostRequest()
{
CountryCodes = new Collection<string>();
}
/// <summary>
/// Gets or sets the Countries list
/// </summary>
[XmlArray("Country")]
[XmlArrayItem("Code")]
//[DataMember(Name = "CountryCodes")]
public Collection<string> CountryCodes { get; set; }
}
这样一来,由WCF形成的RESTful web service就可以用标准的XML格式与任意调用的客户端进行通讯了。