Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API: Content in HttpResponseMessage

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!

like image 875
Karan Avatar asked Sep 24 '12 10:09

Karan


People also ask

How do I pass content in HttpResponseMessage?

Several months ago, Microsoft decided to change up the HttpResponseMessage class. Before, you could simply pass a data type into the constructor, and then return the message with that data, but not anymore. Now, you need to use the Content property to set the content of the message.

What is HttpResponseMessage in Web API?

HttpResponseMessage. If the action returns an HttpResponseMessage, Web API converts the return value directly into an HTTP response message, using the properties of the HttpResponseMessage object to populate the response. This option gives you a lot of control over the response message.

How do I read http response messages?

You can use ReadAsStringAsync on the Content . var response = await client. SendAsync(request); var content = await response.


1 Answers

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

like image 109
Filip W Avatar answered Oct 12 '22 12:10

Filip W