In WCF, by using the MessageHeader attribute, you can add a soap header for messages:
[MessageContract] public class SoapTest { [MessageHeader] public int Id { get; set; } }
And now by implementing the IClientMessageInspector members, you can add your own custom message header in BeforeSendRequest method:
public class MessageInspector : IClientMessageInspector { public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { } public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel) { MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue); request = buffer.CreateMessage(); Console.WriteLine("Sending:\n{0}", buffer.CreateMessage().ToString()); return null; } }
Rather than the solution above, there is another library named wcfextrasplus which is more straightforward. Look at the class below:
public partial class SoapHeadersSampleClient { public Header MyCustomHeader { get { return InnerChannel.GetHeader<Header>("CustomHeader"); } set { InnerChannel.SetHeader("CustomHeader", value); } } }
And now you can use the CustomHeader like this:
public void TestHeaders() { var client = new SoapHeadersSampleClient() { MyCustomHeader = new Header() { Value = "Test" } }; var result = client.In(); client.Out("Testing output"); result = client.MyCustomHeader.Value; }
but I personally like the first solution!