Tuesday 2 August 2011

Making a Restful WCF service vary its response

A natural fit with the HTTP architecture is to have a WCF service vary the response contents according to the MIME type set in the Accept header by the client.

Whilst this is easy to do using the WCF Web API, it is slightly more challenging in an application using regular WCF (even WCF 4).

The specific scenario I needed to handle was:

  1. Given a request for a resource.
  2. When the Accept header is not set, respond with the appropriate default representation (e.g. XML/JSON object).
  3. When the Accept header is set to a relevant MIME type, e.g. application/png, respond with a stream containing the PNG representation of the resource.
  4. Due to the architecture being used, the method's response type could not be the Message type, but had to be that which represented the default resource representation.

The solution I finally arrived at was greatly added by this great post on IOperationBehaviour and the WCF Web API PngResponseFormatter. A sample solution can be downloaded as a zipped VS 2010 solution.

No comments: