我应该在 .Net Web Api 2 中返回状态代码还是抛出异常

sea*_*ght 5 c# asp.net exception-handling httpresponse asp.net-web-api2

我曾见过这样的例子

public IHttpActionResult GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return Ok(item);
}
Run Code Online (Sandbox Code Playgroud)

但我也想象这是一个选择

public IHttpActionResult GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        return NotFound();
    }
    return Ok(item);
}
Run Code Online (Sandbox Code Playgroud)

抛出异常或简单地返回 NotFound(IHttpActionResult 实例)是否有优势?

我知道在响应/请求管道中有一些阶段可以处理这些结果中的任何一个,就像第一个例子一样

public class NotFoundExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotFoundException)
        {
            // Do some custom stuff here ...
            context.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
    }
}

...

GlobalConfiguration.Configuration.Filters.Add(
    new ProductStore.NotFoundExceptionFilterAttribute());
Run Code Online (Sandbox Code Playgroud)

Cla*_*ies 4

IHttpActionResult是 WebApi 2 中添加的一项功能。WebApi 1 中的传统方法(即创建HttpResponseMessage或抛出 )HttpResponseException仍然可供您使用,但IHttpActionResult开发它是为了简化流程。

IHttpActionResult接口有一种方法:

public interface IHttpActionResult
{
    Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
Run Code Online (Sandbox Code Playgroud)

NotFound方法只是创建一个NotFoundResult返回空响应的HttpStatusCode.NotFound。这本质上与 throw 的作用完全相同HttpResponseException(HttpStatusCode.NotFound),但语法更统一。

IHttpActionResult界面还允许您轻松创建自定义ActionResult类以返回HttpStatusCode您想要的任何或任何内容类型。