Running the Content Negotiation (Conneg) Manually in ASP.NET Web API

In this post we will see how run the Content Negotiation (Conneg) manually in an ASP.NET Web API easily.
21 June 2012
2 minutes read

Related Posts

I just wanted to put this out to the World to show how we can run content negotiation manually. As far as I remember, Daniel Roth showed this on his TechEd NA 2012 talk (Building HTTP Services with ASP.NET Web API) as well.

Why on god's green earth do we want do this? So far, I haven’t been able to find any reason since all the necessary places have either methods or extension methods which does this in behalf of us. Anyway, here is the code that does the trick.

public class CarsController : ApiController {

    public string[] Get() {

        var cars = new string[] { 
            "Car 1",
            "Car 2",
            "Car 3"
        };

        var contentNegotiator = Configuration.Services.GetContentNegotiator();
        var connegResult = contentNegotiator.Negotiate(
            typeof(string[]), Request, Configuration.Formatters
        );

        //you have the proper formatter for your request in your hand
        var properFormatter = connegResult.Formatter;

        //you have the proper MediaType for your request in your hand
        var properMediaType = connegResult.MediaType;

        return cars;
    }
}

First of all, we grab the registered IContentNegotiator from the DefaultServices. The dafault content negotiator is DefaultContentNegotiator and you can replace it with your own implementation easily if you need to. Then, we run the Negotiate method of IContentNegotiator by providing the necessary parameters as described below:

  • First parameter we pass is the type of the object that we would like to send over the wire.
  • The second one is the HttpRequestMessage and we grab that value through the Request property of ApiController.
  • The last parameter is the list of formatters. We grab the registered formatters from the HttpConfiguration object.

There we have it. This method returns us a ContentNegotiationResult instance which carries the chosen proper MediaTypeFormatter and the MediaTypeHeaderValue. In the above sample, I don’t do anything with it and it doesn’t effect the behavior in any way but you might have an edge case where you might need something like this.