在大多数情况下,开发者只关心数据契约而不必考虑携带这些数据的消息,然而某些特殊情况下,需要完全控制SOAP消息 的结构,如提供户操作性,或者控制消息的某一部分的安全性,此时可以使用WCF中提供的编程模型消息契约,它使用一种可直接序列化为所需精确SOAP消息 的类型。如果为某一个数据类型定义了消息契约,我们可以完全控制该类型和SOAP消息之间的映射,如下面的代码:
[MessageContract ]
public class CustomerMessage
{
[MessageHeader ]
public Guid Id { get ; set ; }
[MessageBodyMember ]
public String Name { get ; set ; }
[MessageBodyMember ]
public String Email { get ; set ; }
}
此处使用MessageContract特性指定CustomerM
essage类型为消息契约,并用MessageHeader指定Id属性在 SOAP消息的标头,用MessageBodyMember指定Name、Email作为SOAP消息的正文,如果拦截到SOAP消息,可以看到如下所 示:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1"
xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
http://tempuri.org/ICustomerContract/GetCustomerResponse
</Action>
<h:Id xmlns:h="http://tempuri.org/">
38097c1d-366d-4c58-84a5-93525766630c
</h:Id>
</s:Header>
<s:Body>
<CustomerMessage xmlns="http://tempuri.org/">
<Email>lhj_cauc[@@AT@@]163.com</Email>
<Name>TerryLee</Name>
</CustomerMessage>
</s:Body>
</s:Envelope>
当然,还可以在消息契约中使用数组,对消息的部分进行签名和加密等操作以及指定标头和正文部分的命名空间,这些不是本文的重点,将不再阐述。可以看到,消息契约为开发者完全控制SOAP消息和自定义类型之间的映射,提供了一种非常方便的途径。
http://tech.ddvip.com/2008-11/122699056193240.html