How do I add a custom header to every WCF message?

One thing I still haven’t managed to do is create my proxy in such a way that a custom header is added to every call that is made through that proxy.
Currently, this is done by instantiating a new OperationContext around each call through the proxy. This can be optimized in several ways:
1) Create a shared OperationContext object and always instatiate the OperationContextScope with it:
using (OperationContextScope scope = new    
            OperationContextScope(standardContextObject))
{
   …
}

I don’t know if it’s a good idea, though. Should OperationContext objects be persisted between calls, or would it have unexpected side effects?

2) Create a wrapper around the OperationContextScope class that fills the OperationContext with the proper headers:

public class MyOperationContextScope : IDisposable
{
   OperationContextScope contextScope;

   public MyOperationContextScope ()
   {
      contextScope = new OperationContextScope();
      MessageHeader standardHeader = new   
      MessageHeader(“StringHeaderValue”).GetUntypedHeader(“StringHeader”, “ns”);
      OperationContext.Current.OutgoingMessageHeaders.Add(standardHeader );
    }

    public void Dispose()
    {
      if (contextScope != null)
      {
          contextScope.Dispose();
      }
    }     
 }

This is a bit cleaner, but still requires me to wrap every proxy call with a using() statement.

Is there a way to interecept all calls and have my headers added automatically?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.