Adding Custom SOAP Headers in WCF 3.5
Programmatically adding custom headers to SOAP messages in Windows Communication Foundation enables advanced scenarios like routing, logging, and distributed tracing without modifying service contracts.
Use Cases for Custom Headers
Custom SOAP headers allow you to pass metadata and routing information separately from business data:
- Content-based routing: Route messages to different servers based on header values
- Correlation tracking: Pass correlation IDs for distributed tracing
- Multi-tenancy: Identify tenant context without polluting business logic
Implementation
Use OperationContextScope to add headers to outgoing messages:
ServicioFuncionarioClient sv = new ServicioFuncionarioClient();
using (new OperationContextScope(sv.InnerChannel))
{
// Add local server routing header
MessageHeader headerLocal = MessageHeader.CreateHeader(
"Key",
"http://serviciosproduccionCP",
"HostCP");
OperationContext.Current.OutgoingMessageHeaders.Add(headerLocal);
// Add remote server routing header
MessageHeader headerBogota = MessageHeader.CreateHeader(
"Key",
"http://serviciosproduccionBogota",
"HostBogota");
OperationContext.Current.OutgoingMessageHeaders.Add(headerBogota);
// Make the service call with custom headers
resultado = sv.FuncionarioLogin(login, passWord);
}
sv.Close();
Key Concepts
OperationContextScope
Creates a scope where outgoing message headers can be modified. Must wrap the service call and is automatically disposed when the scope exits.
MessageHeader Structure
The header contains three components:
- • Name: Header element name (e.g., "Key")
- • Namespace: XML namespace for the header
- • Value: The actual data being transmitted
Important Notes
- WCF 4.0 Enhancement: Later versions support declarative header configuration in config files
- Protocol Support: Not all bindings support custom headers (e.g., basicHttpBinding has limitations)
- Scope Lifetime: Headers only apply within the OperationContextScope block
Modern Context
Note: While WCF 3.5 required programmatic header manipulation, modern protocols handle metadata differently. HTTP/2 and gRPC use native header mechanisms, GraphQL uses context objects, and REST APIs typically use HTTP headers directly. The fundamental concept of separating metadata from payload remains universal across all service architectures.