To redirect before a specific action is called

Page creation date :

when you visit a site you build in ASP.NET MVC, the URL and routing will call the corresponding controller action, but in some situations you may want to redirect it to another action or page before the corresponding action is called.

If you want each action to redirect, you can use RedirectResult or RedirectToRouteResult to solve it, but you can use the Controller.OnActionExecuting override method if you want to redirect in common before each action is called. This method is the method that is handled before each action is called.

If you want the Controller.OnActionExecuting method to redirect:

public class MyController : Controller
  // 各アクションが呼ばれる前に呼ばれるメソッド
  public override void OnActionExecuting(ActionExecutingContext filterContext)
    if (リダイレクトさせる条件)
      filterContext.Result = new RedirectResult(url);

If you set a RedirectResult with a URL in ActionExecutingContext.Result, you redirect to the specified URL. If you do not branch with an if statement, a redirect is performed on all actions that belong to the target controller.

You can also set a common Controller class for each Controller class base class and implement the OnActionExecuting method to share processing with multiple Controller classes.

"ActionExecutingContext.Result" is an ActionResult type, so you can use the RedirectToRouteResult class or the Controller.RedirectToAction method.