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:
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.