Friday, June 22, 2012

Dynamic Response Formats with WCF REST 4

I recently had a need to return data from a RESTful service in more than one format.  The consumers of the service had varying needs, some preferred XML, others wanted JSON.  WCF REST 4 provides both types of output serialization very simply by decorating your exposed method with the ResponseFormat attribute:

[WebGet(UriTemplate = "/SomeData/?dataId={categoryId}", ResponseFormat = WebMessageFormat.Json)]

However, what do you do if you want to set the output type based on the consumer's preference?  The key is to modify the OutgoingResponse.Format property of the WebOperationContext object per the caller's preferences.

[WebGet(UriTemplate = "/SomeData/?dataId={categoryId}&format={format}"
public class DataObjects SomeData(int dataId, string format)
{
if (format == "json")
   WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
...

Now your consumer can specify which output formatter is appropriate for their situation.  This wreaks havoc with the auto generated WSDL and may not be appropriate for public APIs but works well on services with known target audiences.

No comments:

Post a Comment