Web API: Content in HttpResponseMessage

Karan picture Karan · Sep 24, 2012 · Viewed 61k times · Source

In one of my Get request, I want to return an HttpResponseMessage with some content. Currently I have it working as follows:

var header = new MediaTypeHeaderValue("text/xml");
Request.CreateResponse(HttpStatusCode.OK, myObject, header);

However, since I am using the static Request, this becomes really difficult to test. From what I have read, I should be able to do the following:

return new HttpResponseMessage<T>(objectInstance);

However, seem to not be able to do this. Is it because I am using a older version of WebApi / .NET?


On a side note, I found that you could potentially create a response as follows:

var response = new HttpResponseMessage();
response.Content = new ObjectContent(typeof(T), objectInstance, mediaTypeFormatter);

What puzzled me is why do I have to add a mediaTypeFormatter here. I have added the media type formatter at the global.asax level.

Thanks!

Answer

Filip W picture Filip W · Sep 24, 2012

HttpResponseMessage<T> was removed after Beta. Right now, instead of a typed HttpResponseMessage we have a typed ObjectContent

If you manually create HttpResponseMessage using its default parameterless constructor, there is no request context available to perform content negotiation - that's why you need to specify the formatter, or perform content negotiation by hand.

I understand you don't want to do that - so use this instead:

HttpResponseMessage response = Request.CreateResponse<MyObject>(HttpStatusCode.OK, objInstance);

That would create the response message relying on the content negotiation performed against the request.

Finally, you can read more about content negotiation here On this link