.net Web API:HttpResponseMessage 中的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12563576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Web API: Content in HttpResponseMessage
提问by Karan
In one of my Get request, I want to return an HttpResponseMessage with some content. Currently I have it working as follows:
在我的一个 Get 请求中,我想返回一个包含一些内容的 HttpResponseMessage。目前我的工作方式如下:
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?
但是,似乎无法做到这一点。是不是因为我使用的是旧版本的 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.
令我困惑的是为什么我必须在这里添加一个 mediaTypeFormatter 。我在 global.asax 级别添加了媒体类型格式化程序。
Thanks!
谢谢!
回答by Filip W
HttpResponseMessage<T>was removed after Beta. Right now, instead of a typed HttpResponseMessagewe have a typed ObjectContent
HttpResponseMessage<T>Beta 版后被移除。现在,HttpResponseMessage我们有一个类型而不是类型ObjectContent
If you manually create HttpResponseMessageusing 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.
如果您HttpResponseMessage使用其默认的无参数构造函数手动创建,则没有可用于执行内容协商的请求上下文 - 这就是您需要指定格式化程序或手动执行内容协商的原因。
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
最后,您可以在此链接上阅读有关内容协商的更多信息

