Adding custom soap headers in wcf

July 18, 2011 at 9:11 AMalex

 I’ve researched on the topic of SOAP header support in WCF and it seems that there are two primary ways for interaction with headers:

1.     Message contract definition:

WCF message contracts this also easily allows you to define and set WCF SOAP headers.

[MessageContract]
public class BankingTransaction
{
  [MessageHeader]
  public Operation operation;
  [MessageHeader] 
  public DateTime transactionDate;
  [MessageBodyMember] 
  private Account sourceAccount;
  [MessageBodyMember] 
  private Account targetAccount;
  [MessageBodyMember] 
  public int amount;
}

Here, the "operation" and the "transactionDate" are defined as SOAP headers.

2.     Inspecting headers via WCF Behaviors.
The client side
IClientMessageInspector defines two methods BeforeSendRequest and AfterReceiveReply
while the server side
IDispatchMessageInspector has the opposite methods, i.e. AfterReceiveRequest and BeforeSendReply.

With this, you could add headers to every message going across the wire (or selectively only to a few).

Here's a snippet from a IClientMessageInspector implementor:

public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
    …
    request.Headers.Add(header);

    return null;
}

            There is a library on Codeplex WCF Extras it's an easy extension library for WCF which offers custom SOAP headers.

If clients are on .NET 2.0 and not using WCF this should still work just fine. Wecould still use the message inspector on the server side to sniff and extract the custom headers being sent by your .NET 2.0 clients. More details are here: Custom SOAP Headers: WCF and SMX. 

Posted in: Development | R&D

Tags:

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading