【问题标题】:Setting exception handled in Web API ExceptionFilterAttribute设置在 Web API ExceptionFilterAttribute 中处理的异常
【发布时间】:2013-05-02 18:11:11
【问题描述】:

在 ASP.NET Web API 中有什么方法可以将异常标记为在 ExceptionFilterAttribute 中处理?

我想使用异常过滤器在方法级别处理异常,并停止传播到全局注册的异常过滤器。

用于控制器动作的过滤器:

public class MethodExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotImplementedException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(context.Exception.Message)
            };
            // here in MVC you could set context.ExceptionHandled = true;
        }
    }
}

全局注册的过滤器:

public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is SomeOtherException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.SomethingElse)
            {
                Content = new StringContent(context.Exception.Message)
            };
        }
    }
}

【问题讨论】:

  • 能否请您放一个“使用异常过滤器在方法级别处理异常”的示例?
  • 为了进入全局过滤器,我认为首先必须在方法中处理异常 - 那么为什么不将不安全的代码包装在 try/catch 块中并在那里处理呢?

标签: asp.net asp.net-web-api


【解决方案1】:

尝试在本地处理结束时抛出HttpResponseException。按照设计,它们不会被异常过滤器捕获。

throw new HttpResponseException(context.Response);

【讨论】:

  • 旧答案,但我只是想指出,这并不妨碍进行更多处理。
【解决方案2】:

Web API 2 的设计考虑了inversion of control。您考虑已经处理异常的可能性,而不是在处理后中断过滤器执行。

从这个意义上说,从ExceptionFilterAttribute 派生的属性应该检查是否已经处理了异常,因为is 运算符为null 值返回false,您的代码已经这样做了。另外,处理完异常后,为了避免进一步处理,将context.Exception设置为null

要在您的代码中实现这一点,您需要将 MethodExceptionFilterAttribute 中的注释替换为 context.Exception = null 以清除异常。

请务必注意,由于排序问题,注册多个全局异常过滤器并不是一个好主意。 Web API中属性过滤器的执行顺序,请看下面的线程Order of execution with multiple filters in web api

【讨论】:

    猜你喜欢
    • 2015-05-14
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2017-10-11
    • 2014-06-12
    • 2012-05-04
    • 2016-12-02
    相关资源
    最近更新 更多