在WCF中有两种契约各自是DataContract和MessageContract,这篇博客来讲一下两者的差别。先看一下两者定义契约实体的方式有和不同。
1.数据契约
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; namespace EmployeeService { [DataContract(Namespace="http://Employee/employee")] public class Employee { private int _id; private string _name; private string _gender; private DateTime _dateOfBirth; [DataMember(Name="id",Order=1)] public int ID { get { return _id; } set { _id = value; } } [DataMember(Name = "Name", Order = 2)] public string Name { get { return _name; } set { _name = value; } } [DataMember(Name = "Gender", Order = 2)] public string Gender { get { return _gender; } set { _gender = value; } } public DateTime DateOfBirth { set { _dateOfBirth = value; } get { return _dateOfBirth; } } } } </span></span>
2.消息契约
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; using System.ServiceModel; namespace EmployeeService { [MessageContract(IsWrapped=true,WrapperName="EmployeeInfoObject",WrapperNamespace="http://Employee")] public class Employee { private int _id; private string _name; private string _gender; private DateTime _dateOfBirth; [MessageBodyMember(Order=1,Namespace="http://Employee")] public int ID { get { return _id; } set { _id = value; } } [MessageBodyMember(Order = 2, Namespace = "http://Employee")] public string Name { get { return _name; } set { _name = value; } } [MessageBodyMember(Order = 3, Namespace = "http://Employee")] public string Gender { get { return _gender; } set { _gender = value; } } [MessageBodyMember(Order = 4, Namespace = "http://Employee")] public DateTime DateOfBirth { set { _dateOfBirth = value; } get { return _dateOfBirth; } } } } </span></span>
3.差别一:DataContract gives very limited control over the SOAP message.
我们在先前的博客中也提到过,通过採用数据契约的方式能够改变XML元素在主体部分中的位置。仅仅有这些,因此数据契约并没有太多的控制对SOAP协议。
4. MessagecContract gives full control.
与数据契约比較的话。消息契约能够做到全然的控制SOAP协议,比方生成的XML元素header和body部分。因此採用消息契约的话,能够全然控制SOAP协议。因此也能够对我们一些敏感的信息做一下保护。
具体请參考:消息契约(Message Contract)和基于消息契约的序列化