MVC 5 Redirect from the global.asax to controller action

MVC 5 Redirect from the global.asax to controller action

We can redirect to controller actions from global.asax in mvc 5 using RedirectToControllers() method. The RedirectToControllers() method provided by MVC 2 + versions. 

The below example might help you.

// Get the authentication cookie.
// If the cookie is null then redirect to controller action.
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
     // Get the authentication cookie.
      string cookieName = FormsAuthentication.FormsCookieName;
      HttpCookie authCookie = Context.Request.Cookies[cookieName];

     // If the cookie is null then redirect to controller action.
      if (authCookie == null)
      {
          RedirectToControllers("Account", "Login");
      }
}

// Clear the response. 
// Clear the server errors. 
// Create the route using RouteData (controller/action).
 // Name of controller where you wants to redirect.

private void RedirectToControllers(string control, string action)
{
      Response.Clear();
      Server.ClearError();

      var route = new RouteData();
      route.Values["controller"] = control;
      route.Values["action"] = action;

      // Name of controller where you wants to redirect.
      IController controller = new AlertsController();

      var RequestCont= new RequestContext(new HttpContextWrapper(Context),route);
      controller.Execute(RequestCont);
}
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.