c# - 使用 ASP.NET Web API 进行错误处理的最佳实践

标签 c# asp.net asp.net-web-api exception-handling

您能否阐明 Web API 错误管理的最佳实践是什么?实际上,我不知道在我的 Api 请求中使用 try catch 是否是一个好习惯。

public Vb.Order PostOrderItem(Vb.Order order)
{
    if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        throw new HttpResponseException(httpResponseMessage);
    }
    if (!ModelState.IsValid)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
        throw new HttpResponseException(httpResponseMessage);
    }

    try
    {
        return Vb.Document.Generate(order);
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
        httpResponseMessage.Content = new StringContent(ex.Message);
        throw new HttpResponseException(httpResponseMessage);
    }

}

我觉得对服务器端代码使用 try catch 并不是一个好的做法,因为我只是记录我的 catch 并重新抛出异常。

最佳答案

Web API 中的错误处理被认为是一个横切关注点,应该放在管道中的其他地方,这样开发人员就不需要关注横切关注点。

你应该读一读 Exception Handling in ASP.NET Web API

What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.

还有Global Error Handling in ASP.NET Web API 2

您应该尽量保持您的 Controller 精简。像您的原始代码那样进行错误处理只会导致代码重复,并让开发人员意识到不必要的担忧。开发人员应该关注核心问题,而不是横切问题。通过只关注核心问题,上面的代码将如下所示:

[MyAuthentication]
[MyValidateModel]
public Vb.Order PostOrderItem(Vb.Order order)
{    
    return Vb.Document.Generate(order);
}

为什么这么瘦?

因为:

if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true)
{
    HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
    throw new HttpResponseException(httpResponseMessage);
}

可移入Authentication Filters in ASP.NET Web API 2 可以在 Controller /操作上局部应用或全局应用以返回相关响应。

Model Validation in ASP.NET Web API像这样

if (!ModelState.IsValid)
{
    HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
    throw new HttpResponseException(httpResponseMessage);
}

也可以移动到过滤器中,例如:。

public class MyValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

关于c# - 使用 ASP.NET Web API 进行错误处理的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38025305/

相关文章:

c# - NAT 在其表中保留 TCP 转换字段多长时间?

c# - 访问文件系统 Azure 应用服务

c# - 写入然后从 MemoryStream 读取

asp.net - 翁布拉科 7 : Get all siblings from current page

c# - 如何在.net core WebApi 上获取请求字符串

c# - 将 EntityFramework 6.0.0.0 还原为 5.0.0.0

c# - JSON 字符串上的字符串 'Input string was not in a correct format' 异常

asp.net - 许可 .Net 网站

asp.net - JQueryUI 和 ASP.NET UpdatePanel 之争?有什么快速的替代方案吗?

javascript - knockout : Accessing property of observable object