How to redirect from OnActionExecuting in Base Controller?

C#asp.net MvcOnactionexecuting

C# Problem Overview


I have tried two ways: Response.Redirect() which does nothing, as well as calling a new method inside of the Base Controller that returns an ActionResult and have it return RedirectToAction()... neither of these work.

How can I do a redirect from the OnActionExecuting method?

C# Solutions


Solution 1 - C#

 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
    ...
    if (needToRedirect)
    {
       ...
       filterContext.Result = new RedirectResult(url);
       return;
    }
    ...
 }

Solution 2 - C#

It can be done this way as well:

filterContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary
    {
        {"controller", "Home"},
        {"action", "Index"}
    }
);

Solution 3 - C#

Create a separate class,

    public class RedirectingAction : ActionFilterAttribute
    {
      public override void OnActionExecuting(ActionExecutingContext context)
      {
        base.OnActionExecuting(context);

        if (CheckUrCondition)
        {
            context.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Home",
                action = "Index"
            }));
        }
      }
   }

Then, When you create a controller, call this annotation as

[RedirectingAction]
public class TestController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Solution 4 - C#

If the redirected controller inherit from the same baseController where we override the OnActionExecuting method cause recursive loop. Suppose we redirect it to login action of account controller, then the login action will call OnActionExecuting method and redirected to the same login action again and again

... So we should apply a check in OnActionExecuting method to check weather the request is from the same controller if so then do not redirect it login action again. here is the code:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
   try
   {
      // some condition ...
   }
   catch
   {
      if (filterContext.Controller.GetType() != typeof(AccountController))
      {
         filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
              { "controller", "Account" }, 
              { "action", "Login" } 
         });
      }
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMetaGuruView Question on Stackoverflow
Solution 1 - C#wompView Answer on Stackoverflow
Solution 2 - C#Randy BurdenView Answer on Stackoverflow
Solution 3 - C#K.KirivarnanView Answer on Stackoverflow
Solution 4 - C#abdul hameedView Answer on Stackoverflow