Custom serialization of .NET type

Topics: ASP.NET Web API
Jun 30, 2013 at 7:58 AM

Please consider the following scenario:

Web api receives a requests for some url with either:

Accept: application/json
Accept: text/xml

The request maps to an action named "GetProduct" which return a Product model class

public class Product
public int Id { get; set; }
public string Name { get; set; }

Depending on the accept media type and the action's .NET return type, I want WebApi to invoke my custom serialization code.

For example:
  1. Accept: application/json + Product model will output [1, 'Mike']
  2. Accept text/xml + Product model will output <Results><Result id="1" name="Mike" /></Results>
I looked at media type formatter but these are invoked based on the accept header only and I don't want to define something like "application/json-product" as “format” and “model” are two separate concepts/concerns.

I also looked at HttpResponseMessage with custom formatter, possible manually parsing the accept header in the request to determine the right formatter to instantiate, but I was wondering if there is more clean way where WebApi would automatically select my specific serialization code depending on the media type requested.