Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current MediaTypeFormatter from the Request object, possible?

I would like to get the MediaTypeFormatter from the request object, is this possible ?

So if the request came in as a

    application/json 

then I would like to get the MediaTypeFormatter which should be, in this case, a JsonMediaTypeFormatter.

The reason I need to do this is so that my api methods can support both MediaTypeFormatters (i.e. XML and JSON).

I am returning a HttpResponseMessage and settting the Content to ObjectContent and i am required to pass in the media type formatter, if i hard code this value to json then it isn't going to support xml.

Anyone done something like this ?

Thanks in advance

like image 219
Martin Avatar asked Jan 28 '14 12:01

Martin


1 Answers

You should use Request.CreateResponse method. Do not try to find out the formatter based on media type. ASP.NET Web API does content negotiation for you. What if the request comes with quality factor and stuff? It will get complicated to write all that logic and it is already done in the framework code. All you got to do is to use the method like this - Request.CreateResponse(HttpStatusCode.OK, product); and return the response object instead of setting ObjectContent yourself. Depending on the formatter chosen from conneg, your object will get serialized. Or, do you have a specific scenario where you cannot use this?

like image 183
Badri Avatar answered Nov 20 '22 14:11

Badri