ASP.Net Web API 2 controller custom content negotiation

By default, ASP.net web api 2 automatically delivers xml and json content types without any explicit serialization in controller with the help of content negotiation (conneg).

For example if your controller defines a default Get method that returns some object, on client request this object may be returned as xml or json string without adding explicit serialization code inside the method.

When the client requests uri /api/My/1 with header Accept (or Content-Type) set to ‘application/json’, web api returns json representation of Resouce object. If the request header Accept (or Content-Type) set to ‘application/xml’, then controller returns xml representation of Resource object.

Here No explicit serialization is required for json and xml. If any media type other than json or xml, then custom MediaTypeFormatters can be used. These custom formatters extend either BufferedMediaTypeFormatter or MediaTypeFormatter with some overridden methods and are configured inside WebApiConfig Register method.

What if you want to restrict custom formatter to only one controller. A work around for this scenario is to use a controller attribute with the implementation of Initialize method of IControllerConfiguration interface.

if the client requests uri /api/My/1 with header Accept (or Content-Type) set to ‘application/mytype’ (or ‘text/mytype’), our custom formatter will be invoked.

if a different controller url requested with the new content type ‘application/mytype’, then you may get default configured formatter (the first formatter in the formatters) or a 406 error if no formatters configured.