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.
2012-06-21 12:50
Tugberk Ugurlu


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.



Comments

Ranjan
by Ranjan on Friday, Feb 08 2013 17:34:56 +02:00

I can answer you question on "Why on god's green earth do we want do this?" 

Say you are building a wrapper for the existing services. The best real world senario which you can think of is the REST data from http://www.factual.com which comes as JSON. As of now they don't support other formats of data.

What you can do is build a wrapper and support different formats to return. That's where the Content Negociation comes into picture , you can make use of that , run manually and then select the formatter and return the suitable data based on the client request

New Comment