Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect from exception filter

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?

like image 311
grokky Avatar asked Feb 20 '17 07:02

grokky


People also ask

What is an exception filter?

Exception Filter provides an ability to handle the exception for all the method, controller classes in one place. Exception filters execute when some of the exceptions are thrown from an action. The exception can be anything. This is by creating a class that inherits from IExceptionFilter and FileAttribute interface.

What is exception explain exception filtering and the way to throw Custom exception in detail?

The Exception Filter in the ASP.NET MVC Application is used to handle any exceptions that occur during the ASP.NET MVC Request processing pipeline. The ASP.NET MVC Framework provides one in-built attribute called HandleError which is basically used to handle the unhandled exception in the MVC application.


1 Answers

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.

like image 155
Kevin Gosse Avatar answered Oct 13 '22 01:10

Kevin Gosse