Introduction
Very often, when designing WCF based SOA services, we run into the need of passing some information repeatedly from the client to the service.
One example would be a user identity information like user ID or the client application identifier. The WCF service needs the user ID information for logging purposes. So for each method call, you have to pass that information.
One way would be to pass it as an additional request parameter. But, each and every method call needs to have this parameter(s) repeatedly. Not a very clean solution. Also, if the data type of this parameter changes, all the method signatures and their calls need to be changed.
A better way to handle this requirement is to add this information to the WCF channel header.
Let's code
First of all, we will add the custom header in the proxy constructor. (Hope you are not using Visual Studio to generate the proxies, or your code would be lost the next time you generate it. Proxy generation using Visual Studio is OK initially when you create the service. You do not have to keep on doing it for each change to the service methods. It is very simple to go to the proxy class and do it manually.)
using System.ServiceModel;
using System.ServiceModel.Channels;
public partial class ZipServiceClient :
System.ServiceModel.ClientBase<IZipService>, IZipService
{
public ZipServiceClient()
{
AddCustomHeaderUserInformation(
new OperationContextScope(base.InnerChannel));
}
private static void AddCustomHeaderUserInformation(
OperationContextScope scope)
{
MessageHeader<int> customHeaderUserID =
new MessageHeader<int>(<State.UserIDToken>);
MessageHeader untypedHeaderUserID =
customHeaderUserID.GetUntypedHeader("UserID",
"CustomHeader");
}
The user ID here is being read from State(session)
. You would need to replace it to whatever storage location your information is in. Next, we will read the headers in our service.
using System.Runtime.Serialization;
using System.ServiceModel;
int userID =
OperationContext.Current.IncomingMessageHeaders.GetHeader<int>(
"UserID", "CustomHeader");
Note: These headers are available anywhere behind the WCF service. You can access them on the Service implementation code and from the layer behind the service.
That's it. It is quite straightforward. I hope I didn't miss any detail. Email me if you have any questions.