How do I get the Message Body as Xml?

This was one was interesting as the service was exposed as a fully typed service, but the client wanted to modify some parts of the xml. Ideally you can plug into any part to perform these operations, but the general requirement here was that they needed a simple pointer to the Body and didn’t care much about anything else.

Here is an example how how you can access the body similar to an XElement by using the Message directly.


[ServiceContract(Namespace="")]public interface IClientProxy{    [OperationContract(Action="",        ReplyAction="")]    Message DoWork();}IClientProxy proxy = cf.CreateChannel();Message msg = proxy.DoWork();XNode node = XElement.ReadFrom(msg.GetReaderAtBodyContents());



So the service can return a typed object, but the client doesn’t have to handle the message in the same way. Understanding the Message class here helps you appreciate how the serializer and encoder is decoupled from the message representation. Basically WCF does not constrain the native format of your message on either the producer’s or the consumer’s side. It merely conforms to some rules of invoking a set of abstract classes which you wire up by virtue of specifying the encoder and the serializer.

Though we have XML semantics around with abstract classes like the XmlReader/XmlDictionaryWriter etc in conjuction with the Message class, this doesn’t actually mean that WCF converts everything to XML before it can process the message. It merely uses these to invoke the required parts to obtain things like the header/body and other properties.  The Message however can be represented natively in any form like binary/json/atom/ or any whacky type as long as you wire them up properly and can retrieve them in some manner.

This should give you some insight into how much more powerful the message model is compared to simple RPC style contracts.  With 4.0 and workflow services, you will see this becoming more and more the default way of thinking about messages and services.

MessageToXElement.cs (2.90 kb)