从异常过滤器重定向

问题描述:

我正在使用ASP.NET Core.我的一个控制器调用了引发各种异常的服务.我想在异常过滤器(而不是中间件)中处理它们.

I'm using ASP.NET Core. One of my controllers calls into services which throw various exceptions. I want to handle them in an exception filter (not middleware).

public class MyHandlerAttribute : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext c)
    {
      if (c.Exception is FooException) {
          // redirect with arguments to here
      } 
      else if (c.Exception is FooException) {
          // redirect with arguments to there
      }
      else {
          // redirect to main error action without arguments, as 500
      }
      base.OnException(c);
    }
}

与动作过滤器不同,异常过滤器无法授予我Controller的访问权限,因此我无法执行c.Result = controller.RedirectTo...().

Unlike action filters, an exception filter doesn't give me access to the Controller, so I can't do a c.Result = controller.RedirectTo...().

那我该如何重定向到我的错误操作?

So how do I redirect to my error action?

HttpContext公开在ExceptionContext上,因此您可以将其用于重定向.

The HttpContext is exposed on the ExceptionContext, so you can use it for the redirection.

context.HttpContext.Response.Redirect("...");

还有一个Result属性,但是我不知道在执行过滤器后是否会对其进行解释.值得一试:

There is also a Result property, but I don't know if it'll be interpreted after the execution of the filter. It's worth a try though:

context.Result = new RedirectResult("...");

如果有效,它也应与RedirectToActionResultRedirectToRouteResult一起使用.

If it works, it should also work with RedirectToActionResult or RedirectToRouteResult.