
One of the new features in WCF for .NET 3.5 is the possibility to create REST Services. These services allow you to create services that eat raw HTTP requests with XML in them and return a raw HTTP response with XML content in them. Normally this only works by deserializing objects and serializing objects. It is however perfectly possible to return raw XML.
For this to work you need to have the base class Message as the return type for your webmethods. Furthermore you are going to need the following helper class to write raw XML content to a message body.
public class XmlElementBodyWriter : BodyWriter { XmlElement xmlElement; public XmlElementBodyWriter(XmlElement xmlElement) : base(true) { this.xmlElement = xmlElement; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { xmlElement.WriteTo(writer); } }
Creating a raw XML document and returning that object is just a matter of invoking the helper class with the right information. This can be done using the following small piece of code:
private Message CreateResponseMessage(XmlDocument inputDocument) { XmlElementBodyWriter writer = new XmlElementBodyWriter(inputDocument.DocumentElement); Message msg = Message.CreateMessage(MessageVersion.None, OperationContext.Current.OutgoingMessageHeaders.Action, writer); return msg; }
This trick is especially useful when you want to upgrade an existing webservice to a REST service and that service returns raw XML documents as the result of a web method. Enjoy 🙂