Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
471 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...