我一直在用WebApi开发,已经转移到WebApi2,微软已经引入了一个新的IHttpActionResult接口,似乎建议用于返回一个HttpResponseMessage。我对这个新界面的优点感到困惑。它似乎只是提供了一种稍微简单的方法来创建HttpResponseMessage。
我认为这是“为了抽象而抽象”。我遗漏了什么吗?除了节省一行代码之外,我从使用这个新接口中获得的实际优势是什么?
旧方法(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();
}
}
下面是微软ASP中提到的IHttpActionResult优于HttpResponseMessage的几个优点。网络文档:
简化控制器的单元测试。
将用于创建HTTP响应的通用逻辑移动到单独的类中。
通过隐藏构造响应的底层细节,使控制器动作的意图更加清晰。
但是这里有一些使用IHttpActionResult的其他优点值得一提:
Respecting single responsibility principle: cause action methods to have the responsibility of serving the HTTP requests and does not involve them in creating the HTTP response messages.
Useful implementations already defined in the System.Web.Http.Results namely: Ok NotFound Exception Unauthorized BadRequest Conflict Redirect InvalidModelState (link to full list)
Uses Async and Await by default.
Easy to create own ActionResult just by implementing ExecuteAsync method.
you can use ResponseMessageResult ResponseMessage(HttpResponseMessage response) to convert HttpResponseMessage to IHttpActionResult.
我宁愿为IHttpActionResult实现TaskExecuteAsync接口函数。喜欢的东西:
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
switch ((Int32)_respContent.Code)
{
case 1:
case 6:
case 7:
response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
break;
case 2:
case 3:
case 4:
response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);
break;
}
return Task.FromResult(response);
}
,其中_request是HttpRequest, _respContent是有效负载。