Web API:HttpResponseMessage中的内容

Kar*_*ran 31 .net httpresponse asp.net-web-api mediatypeformatter

在我的一个Get请求中,我想返回带有一些内容的HttpResponseMessage.目前我的工作如下:

var header = new MediaTypeHeaderValue("text/xml");
Request.CreateResponse(HttpStatusCode.OK, myObject, header);
Run Code Online (Sandbox Code Playgroud)

但是,由于我使用的是静态请求,因此测试起来非常困难.根据我的阅读,我应该能够做到以下几点:

return new HttpResponseMessage<T>(objectInstance);
Run Code Online (Sandbox Code Playgroud)

但是,似乎无法做到这一点.是因为我使用的是旧版本的WebApi/.NET吗?


另外,我发现您可能会创建如下响应:

var response = new HttpResponseMessage();
response.Content = new ObjectContent(typeof(T), objectInstance, mediaTypeFormatter);
Run Code Online (Sandbox Code Playgroud)

令我困惑的是为什么我必须在这里添加一个mediaTypeFormatter.我在global.asax级别添加了媒体类型格式化程序.

谢谢!

Fil*_*p W 64

HttpResponseMessage<T>在Beta之后删除了.现在,HttpResponseMessage我们有一个打字,而不是打字ObjectContent

如果HttpResponseMessage使用其默认的无参数构造函数手动创建,则没有可用于执行内容协商的请求上下文 - 这就是您需要指定格式化程序或手动执行内容协商的原因.

我知道你不想这样做 - 所以请改用它:

HttpResponseMessage response = Request.CreateResponse<MyObject>(HttpStatusCode.OK, objInstance);
Run Code Online (Sandbox Code Playgroud)

这将创建依赖于针对请求执行的内容协商的响应消息.

最后,您可以在此链接中阅读有关内容协商的更多信息

  • @RoyDictus我很好奇它为什么让单元测试变得困难,你能详细说明吗? (7认同)
  • 我想念HttpResponseMessage <T>,我认为它是一个更好的API,但Request.CreateResponse <T>工作正常. (4认同)
  • 请记住,任何使用`HttpResponseMessage`的控制器方法都很难进行单元测试,因此如果可以,最好避免使用它. (3认同)