Custom MessageHeaders in WCF


In WCF it can be necessary to define custom message headers, to transport additional data from client to server, without changing the body of the message, you must define custom headers.


Soap Message with additional Header.

<s:Envelope xmlns:s="" xmlns:a="">


    <a:Action s:mustUnderstand="1">helloWorld</a:Action>

    <MyHeader xmlns="http://myExtension/Header" name="test">









Simple Additional Headers can be inserted in to Message with:

MessageHeader header = MessageHeader.CreateHeader("MyHeader","http://myExtension/Header", "test");



For Complex Message Headers you must create an own class which derived from MessageHeader. This class must implement three methods wich serialize the message header and the data in it. It used an XmlWriter so you can write any xml data in this header.


   /// Add the custom header.

   message.Headers.Add(new MyMessageHeader());



   /// Message Header class

   public class MyMessageHeader: MessageHeader


        /// This method writes all header conten in the XmlWriter.

        /// The header elemet is already writed in this writer.

        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)


                writer.WriteAttributeString("name", "test");






        /// The Name of the header element.

        public override string Name


            get { return " MyHeader "; }



        /// The Namespace of the header element

        public override string Namespace


            get { return NamespaceHeader; }





On the Reciver side it is necessary to extract the MessageHeader from the message. There are no methods to do this in the MyMessageHeader class.


Simple Additional Headers can be extracted form a Message with:

int index = message.Headers.FindHeader("MyHeader", "http://myExtension/Header");

string str = message.Headers.GetHeader<string>(index);


For Complex Message Headers can be extracted form a Message with:

int index = message.Headers.FindHeader("MyHeader", "http://myExtension/Header");

XmlReader xmlReader = message.Headers.GetReaderAtHeader(index);


If you need a XmlDocument you must create a SubTreeReader  before you can load the XmlDocument, because the GetReaderAtHeader contains all heades and not only the specified header.


XmlReader myHeaderReader = xmlReader.ReadSubtree();

XmlDocument doc = new XmlDocument();



Posted Jul 27 2006, 04:24 PM by Rolf Nebhuth is a .Net Community Blog powered by daenet GmbH.