WCF Custom Message Headers
Often do we want to pass some data to some or maybe all our service operations. This data is usually context data such as user tokens, or environmental preferences of the user or machine. In these kind of situations, we would rather not add additional context parameters to the contracts or our services, because we don’t want to involve implementation data / context data with the business parameters of our services.
A nice and easy way to pass that data is to use MessageHeaders. In order to do this we follow these steps:
Add the context data to the outgoing message headers.
Call the operation (Nothing special here).
Extract the data from the incoming message headers.
Using an OperationContextScope
In order to add the message header, you should have a OperationContext for your call. An OperationContext will automaticly be created for the call, and will be available in the service side. If one wishes to add the message headers to the OperationContext before the actual operation call, he should use an OperationContextScope, like the following piece of code shown as Code Block 1.
Notice that the value that is being passed to the constructor of OperationContextScope must implement IContextChannel interface.
Adding the context data to the outgoing message headers (client-side)
In the example shown in Code Block 1, there is a Guid token that had to be passed in the message headers. In order to pass it, I created a typed MessageHeader, and than produced an untyped MessageHeader with a name and namespace.
Code Block 1:
using (ChannelFactory<IMyServiceChannel> factory =
new ChannelFactory<IMyServiceChannel>(new NetTcpBinding()))
using (IMyServiceChannel proxy = factory.CreateChannel(…))
using ( OperationContextScope scope =
new OperationContextScope(proxy) )
Guid myToken = Guid.NewGuid();
MessageHeader<Guid> mhg = new MessageHeader<Guid>(myToken);
MessageHeader untyped = mhg.GetUntypedHeader("token", "ns");
Extract the data from the incoming message headers (service-side)
The following code (Code Block 2) shows how simple it is to extract the typed message header from the incoming headers collection of the OperationContext.
Code Block 2:
Code Block 2:
Guid myToken =
You can download the sample project that shows the usage of MessageHeader in the OperationContext from here.
The Samples are all based on the Base Service Solutions that I posted earlier in the Blog.