WCF Custom Header

In some business cases, we need to change header of SOAP message that is sent to WCF service. Depending our scenario, we need to override some properties of header such as “security” element which is required with username and password with encryption. Maybe we should add some properties that are required by service provider. Whatever our scenario is that implementing WCF client endpoint behavior provides a solution.The following classes implement IEndpointBehavior interface which enables adding binding parameters and client behavior. IClientMessageInspector also enables interposition of request before it is sent. We can create CustomHeader instance which is derived by MessageHeader (System.ServiceModel.Channels).


public class AddCustomHeaderBehavior : IEndpointBehavior
{

public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{ }

public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
CustomHeaderMessageInspector headerInspector = new CustomHeaderMessageInspector();
clientRuntime.MessageInspectors.Add(headerInspector);
}

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{ }

public void Validate(ServiceEndpoint endpoint)
{ }
 }

public class CustomHeaderMessageInspector : IClientMessageInspector
{

  public void AfterReceiveReply(ref Message reply, object correlationState)
  { }

  public object BeforeSendRequest(ref Message request, IClientChannel channel)
  {
    CustomHeader ch = new CustomHeader();
    request.Headers.Add(ch);
    return request;
  }
}

public class CustomHeader : MessageHeader
{
   protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
   {
    writer.WriteValue(DataContext.KurumKodu);
   }

 public override string Name
 {
    get { return "KurumKodu"; }
 }

 public override string Namespace
 {
   get { return String.Empty; }
 }
}

The service proxy client instance is created and OrdersByCustomer method is invoked without endpoint behavior.

4

The request and response is captured by Fiddler as follows. The result is no header information is passed to server.

5

After adding client endpoint behavior;

1

Viola 🙂 The header information which contains “KurumKodu” element is passed to server.

3

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s