blog community

Welcome to blog community Sign in | Join | Help
in Search

Willem Meints

Deleting browser cookies ... Best done with a glass of milk

Returning raw XML from a REST WCF Service

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 :)

Published Monday, August 04, 2008 11:50 AM by willemm
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server, by Telligent Systems