I’m having a bit of trouble retrieving body from a wcf message. I am trying to implement WCF message inspector to validate messages against XSD schema.
The soap body looks like following:
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Header xmlns="http://www.test1.com">
<applicationID>1234</applicationID>
</Header>
<GetMatchRequest xmlns="http://www.tempuri.org">test</GetMatchRequest>
</s:Body>
The problem is when I try to get body it only gets partial body message. Gets only header element, ignores GetMatchRequest element(may be because of multiple namespaces…)
I am using following to get message body:
XmlDocument bodyDoc = new XmlDocument();
bodyDoc.Load( message.GetReaderAtBodyContents().ReadSubtree());
I have also tried following:
bodyDoc.Load( message.GetReaderAtBodyContents());
The code above results in error – This document already has a ‘DocumentElement’ node.
Can anyone please help in extracting body from a WCF message?
Thanks
Message.GetReaderAtBodyContents return the reader positioned not at the element, but at its first child. Usually the message body contains only a single root element, so you can load it directly. But in your message it contains multiple root elements (Header and GetMatchRequest), so if you want to load the whole body in a XmlDocument, you need to provide a wrapping element (the XmlDocument can have only one root element). In the example below I use
<s:Body>as the wrapping element, but you could use anything you want. The code simply reads the body until it finds the end element (</s:Body>).