How do I get the Message Body as an XElement?
Note: Cross posted from Sajay.
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.
For example you can get the XElement from the body using a simple operation and use the Message object on the client to get a pointer to the body.
[code:c#]
[ServiceContract(Namespace="https://www.sajay.com/")]
public interface IClientProxy
{
[OperationContract(Action="https://www.sajay.com/getdata",
ReplyAction="https://www.sajay.com/getdataresponse")]
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 classes which you wire up by virtue of specifying the encoder and the serializer. The fact that we have XML semantics around with abstract classes like the XmlReader/XmlDictionaryWriter etc 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. https://msdn.microsoft.com/en-us/library/ms734675.aspx With 4.0 and workflow services, you will see this becoming more and more the default way of thinking about messages and services.