The following is the contents of this article:
- Message Contract
- Why Message Contract
- Source Code Explanation
As I said in the last article, a Data Contract is all about the structure of the data being exchanged between the client and server, whereas a Message Contract is all about the structure of the message being exchanged. By default WCF takes care of creating SOAP messages according to the data and service contracts, but sometimes we need complete control over the content of SOAP messages (header and body) to provide an additional layer of security. In that case a Message Contract plays a vital role. Ok let’s discuss the benefits of a Message Contract with a source code example.
Why a Message Contract
Message Contracts can be used in the following instances.
Sometimes your project requires that session information be exchanged between the client and server to provide an extra layer of security, so it can be passed in SOAP headers rather than adding additional parameters to operations or adding this information as fields in the data itself.
Sometimes you like to have a custom security protocol (by passing WS-Security) and pass credentials or tokens in custom SOAP headers. Also, when you need to or like to encrypt the header information a Message Contract can be used. The downside with this technique is that the client and the service must manually add and retrieve the information from the SOAP header, rather than having the serialization classes associated with the data and the operation contracts do it for you
Entity Changes often
In case of MessageContracts modification the data structure just needs to change the Message Contract and there is no need for the regenerating proxies. In case of a change in DataContracts you need to regenerate the proxy. So a MessageContract is the best choice if your entity changes often.
Source Code Explanation
Refer to the source code attachment for further details.
Session related implementations can use a Message Contract to get complete control of SOAP messages. Also if your entity is dynamic (keeps changing) you can use a Message Contract.