WCF and REST, An approach to using the Content-Type and Accept HTTP Headers for Object Serialization

With the recent release of the WCF REST Starter Kit, Microsoft made implementing REST services via WCF much more approachable.  The Visual Studio templates provided are great and the accompanying videos on channel9 via endpoint.tv are well put together (Ron Jacobs has a good overview of these items).

One of the questions I had when I first started implementing REST services with WCF was how to add support for using the Content-Type and Accept HTTP headers to determine how objects are serialized.  Dino Chiesa had some great suggestions on how to do this and even wrote some sample code to demonstrate one approach.

Then, this past week I saw that Damian Mehers blogged another approach with sample code.  I really liked how the approach Damian used required nothing more than a method Attribute to support dynamic content type detection.

So I started to re-write my REST service to use a combination of the new base classes in the WCF REST Starter Kit and Damian’s DynamicResponse sample.  And I soon realized that it was missing support for dynamic deserialization of requests via the Content-Type header.

To make a long story short, I ended up merging Damian’s project into the Microsoft.ServiceModel.Web project that comes with the WCF REST Starter Kit and adding another method attribute to support incoming requests.  The result was two new method attributes: DynamicResponseType and DynamicRequestType.

Here is a diagram of the different scenarios that are now supported (essentially full bi-directional content-type detection via HTTP headers at a single URI):

scenarios-snapshot

Hopefully this capability will make it into the next WCF REST starter kit.  But for now you can download the code to see the few changes that are required to support this behavior.

Visual Studio solution with full source[NOTE: This code is not supported and is provided as an example only.  Use at your own risk.]

Note that the web project is exactly what you get with the WCF REST Collections service template but modified to not require multiple methods for both JSON and XML support.

It’s pretty amazing that creating a full-featured REST service with WCF now only requires the implementation of five (5) methods.  Great job on the starter kit WCF team and look forward to the next release!

Filed under: ,

Leave a Comment

Comments

  • No Comments

Trackbacks

  • from Pablo M. Cibraro (aka Cibrax) on 05 Dec, 2008

    One of the missing features in the WCF web model is the ability to have a single operation definition