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 ASP.Net MVC 5 using the method - RedirectToControllersThe RedirectToControllers() method provided by MVC 2 + versions. 

Example, it might help you to understand more about the same.

/// <summary>
/// gets the authentication cookie
/// if the cookie is null then redirect to controller action
/// </summary>
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 the controller action.
    if (authCookie == null)
    {
        RedirectToControllers("Account", "Login");
    }
} 

///<summary>
///Clear the response.
/// Clear the server errors.
/// Create the route using RouteData (controller/action)
/// Name of controller where you wants to redirect
/// </summary>
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 want 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 Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

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