从异常过滤器重定向 [英] Redirect from exception filter

查看:125
本文介绍了从异常过滤器重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

这篇关于从异常过滤器重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆