Asp.net 设置Web API ExceptionFilterAttribute中处理的异常

Asp.net 设置Web API ExceptionFilterAttribute中处理的异常,asp.net,asp.net-web-api,Asp.net,Asp.net Web Api,ASP.NET Web API中是否有任何方法将异常标记为ExceptionFilterAttribute中处理的异常 我希望使用异常过滤器在方法级别处理异常,并停止向全局注册的异常过滤器的传播 控制器操作上使用的筛选器: public class MethodExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext co

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)
            };
        }
    }
}
试着在你的本地处理结束时抛出一个。根据设计,它们不会被异常过滤器捕获

throw new HttpResponseException(context.Response);

WebAPI2的设计考虑到了这一点。您认为已经处理异常的可能性,而不是在处理之后中断过滤器执行。

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

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


需要注意的是,由于排序问题,注册多个全局异常过滤器不是一个好主意。有关Web API中属性筛选器的执行顺序的信息,请参阅以下线程。

您可以使用“使用异常筛选器在方法级别处理异常”的示例吗?为了进入全局过滤器,我认为首先必须在方法中不处理异常-那么为什么不将不安全代码包装在
try/catch
块中并在那里处理它呢?旧答案,但我只想指出,这并不妨碍更多的处理。