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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With