How to redirect to login page if session is not available in MVC

I think you could wrap this logic inside an action filter, and redirect in there:

    public class AuthorizeActionFilterAttribute : ActionFilterAttribute
    {
      public override void OnActionExecuting(FilterExecutingContext filterContext)
      {
        HttpSessionStateBase session = filterContext.HttpContext.Session;
        Controller controller = filterContext.Controller as Controller;

        if (controller != null)
        {
          if (session != null && session ["authstatus"] == null)
          {
filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "Login" },
                                          { "action", "Index" }

                                         });
          }
        }

        base.OnActionExecuting(filterContext);
      }
    }

more details in here:

https://stackoverflow.com/a/5453371/1384539


  1. Write code in web.config file to set the session timeout to 2 minutes

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Forms">
            <forms loginUrl="~/Login/Index" timeout="1" />
        </authentication>
        <sessionState timeout="2"></sessionState>
        <globalization uiCulture="en" culture="en-GB"/>
    </system.web>
    
  2. Write the code below in a <script> tag in layout.cshtml

    //session end 
    var sessionTimeoutWarning = @Session.Timeout - 1;
    var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
    setTimeout('SessionEnd()', sTimeout);
    
    function SessionEnd() {
        window.location.hostname = "";
        /* $(window.Location).attr("href", "@Url.Content("~/Login/index/")"); */
        window.location = "/Login/index/";
    }
    
  3. Write the code below in control and action

    [HttpGet]
    public ActionResult Logout()
    { 
        Session["id1"] = null;
        Session["id2"] = null;
        Session["id3"] = null;
        Session["id4"] = null;
        Session["Region"] = null;
        Session.Clear();           
        Session.RemoveAll();
        Session.Abandon();
        Response.AddHeader("Cache-control", "no-store, must-revalidate, private, no-cache");
        Response.AddHeader("Pragma", "no-cache");
        Response.AddHeader("Expires", "0");
        Response.AppendToLog("window.location.reload();");
    
        return RedirectToAction("Index", "Login");
    }