6
votes

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

1
The Web API framework automatically handles selecting the correct MediaTypeFormatter based on the Accept header sent in the request. You should not need to be concerned with setting the response content type in your API methods unless you're doing something special. Let the framework handle it; that is what it is designed for. See @Badri's answer.Brian Rogers

1 Answers

11
votes

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?