Friday, July 27, 2012

Returning raw data using WCF Rest 4

Sometimes you need full control over the content your are delivering to your http client.  You want to set the headers, you want to stream data from a disk or a database, or maybe you just want to send out data that doesn't get mangled by serializers.  This is easy to do with WCF REST projects.

        [WebGet(UriTemplate = "/SomeXmlThing")]
        public Stream OutputXmlData(string someInputParameter)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";

            string someXml = "<xmlData><notfullyFormedXML /></xmlData>";
            byte[] resultsBytes = Encoding.UTF8.GetBytes(someXml);
            return new MemoryStream(resultsBytes);
        }

By returning Stream, any data can be sent over the http channel.  With the proper content type set you can easily return any form of data using the stream such as images, raw xml, text, binaries, etc...  In this particular code sample the raw xml is returned without being touched by the XML serializer, which allows the raw xml to be passed directly to the client.  If this was done by returning string, the string would be passed through the XML serializer and encoded as text.