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.
6/21/2012 12:50:00 PM
2 comments
2234 times
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. Comments
#2816
re: Running the Content Negotiation (Conneg) Manually in ASP.NET Web API
by Ranjan on 02/08/13 17:34:56 Friday (UTC +00: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 Additional allowed tags : [quote]...[/quote], [user]...[/user]
|
Keep in Touch with MeTagsArchive
Blogroll |





This is explained in the official tutorials as well: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation