Web API:HttpResponseMessage 中的内容 [英] Web API: Content in HttpResponseMessage
问题描述
在我的一个 Get 请求中,我想返回一个包含一些内容的 HttpResponseMessage.目前我的工作方式如下:
var header = new MediaTypeHeaderValue("text/xml");Request.CreateResponse(HttpStatusCode.OK, myObject, header);
然而,由于我使用的是静态请求,这变得非常难以测试.根据我的阅读,我应该能够做到以下几点:
return new HttpResponseMessage(objectInstance);
但是,似乎无法做到这一点.是不是因为我使用的是旧版本的 WebApi/.NET?
<小时>顺便说一句,我发现您可能会创建如下响应:
var response = new HttpResponseMessage();response.Content = new ObjectContent(typeof(T), objectInstance, mediaTypeFormatter);
令我困惑的是为什么我必须在这里添加一个 mediaTypeFormatter.我在 global.asax 级别添加了媒体类型格式化程序.
谢谢!
HttpResponseMessage
在 Beta 版之后被移除.现在,我们有一个类型化的 ObjectContent
HttpResponseMessage
如果您使用其默认的无参数构造函数手动创建 HttpResponseMessage
,则没有可用于执行内容协商的请求上下文 - 这就是您需要指定格式化程序或手动执行内容协商的原因.>
我知道你不想这样做 - 所以改用这个:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, objInstance);
这将创建依赖于针对请求执行的内容协商的响应消息.
最后,您可以在此处阅读有关内容协商的更多信息 在这个链接上
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!
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
这篇关于Web API:HttpResponseMessage 中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!