问题描述
我一直在使用 WebApi 进行开发,并已转向 WebApi2,其中 Microsoft 引入了一个新的 IHttpActionResult
接口,似乎建议使用该接口而不是返回 HttpResponseMessage
.我对这个新界面的优势感到困惑.它似乎主要只是提供一种轻微更简单的方法来创建HttpResponseMessage
.
I have been developing with WebApi and have moved on to WebApi2 where Microsoft has introduced a new IHttpActionResult
Interface that seems to recommended to be used over returning a HttpResponseMessage
. I am confused on the advantages of this new Interface. It seems to mainly just provide a SLIGHTLY easier way to create a HttpResponseMessage
.
我认为这是为了抽象而抽象".我错过了什么吗?除了可能会节省一行代码之外,我从使用这个新界面中获得的现实世界优势是什么?
I would make the argument that this is "abstraction for the sake of abstraction". Am I missing something? What is the real world advantages I get from using this new Interface besides maybe saving a line of code?
旧方法(WebApi):
public HttpResponseMessage Delete(int id)
{
var status = _Repository.DeleteCustomer(id);
if (status)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
新方式(WebApi2):
public IHttpActionResult Delete(int id)
{
var status = _Repository.DeleteCustomer(id);
if (status)
{
//return new HttpResponseMessage(HttpStatusCode.OK);
return Ok();
}
else
{
//throw new HttpResponseException(HttpStatusCode.NotFound);
return NotFound();
}
}
推荐答案
您可能决定不使用 IHttpActionResult
,因为您现有的代码构建了不适合的 HttpResponseMessage
预设答案之一.但是,您可以使用 ResponseMessage
的预设响应将 HttpResponseMessage
调整为 IHttpActionResult
.我花了一段时间才弄明白这一点,所以我想发布它,表明您不必选择其中之一:
You might decide not to use IHttpActionResult
because your existing code builds a HttpResponseMessage
that doesn't fit one of the canned responses. You can however adapt HttpResponseMessage
to IHttpActionResult
using the canned response of ResponseMessage
. It took me a while to figure this out, so I wanted to post it showing that you don't necesarily have to choose one or the other:
public IHttpActionResult SomeAction()
{
IHttpActionResult response;
//we want a 303 with the ability to set location
HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
responseMsg.Headers.Location = new Uri("http://customLocation.blah");
response = ResponseMessage(responseMsg);
return response;
}
注意,ResponseMessage
是你的控制器应该继承的基类 ApiController
的一个方法.
Note, ResponseMessage
is a method of the base class ApiController
that your controller should inherit from.
这篇关于为什么我应该使用 IHttpActionResult 而不是 HttpResponseMessage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!