Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

.net - 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!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...