Redirect from exception filter

不羁的心 提交于 2019-12-07 09:16:36

问题


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);
    }
}

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?


回答1:


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

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

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("...");

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



来源:https://stackoverflow.com/questions/42338966/redirect-from-exception-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!