Adding custom SOAP envelope header fields in C# WCF client applications

Posted: (EET/GMT+2)

 

Sometimes you need to send custom header fields with your WCF SOAP requests, for example, things like authentication tokens or correlation IDs that are not part of the method parameters.

You can do this by adding a MessageHeader in a custom behavior or directly before calling the service. Here's an example of adding a custom header to a WCF client call:

var client = new MyServiceClient();
using (new OperationContextScope(client.InnerChannel))
{
    var header = MessageHeader.CreateHeader("ClientToken", "http://tempuri.org", "ABC123");
    OperationContext.Current.OutgoingMessageHeaders.Add(header);

    var result = client.GetData(42);
}

The CreateHeader method takes the header name, namespace, and value. The header appears in the SOAP envelope alongside the default headers.

On the service side, you can read the header like this:

var headers = OperationContext.Current.IncomingMessageHeaders;
int index = headers.FindHeader("ClientToken", "http://tempuri.org");
if (index >= 0)
{
    string token = headers.GetHeader<string>(index);
}

SOAP headers are useful when you need cross-cutting metadata that applies to multiple operations without changing the service contracts.