Detect Session Timeout

  • 696 Views
  • Last Post 23 January 2019
IrsanIskandar posted this 20 October 2018

Please help with my problem, i want to get the session time, if the session has run out it will be switched to another page.

Thank you regards.

lucy posted this 23 January 2019

To detect session time out in asp.net, you can add a config to asp.net as shown below.

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" protection="All" timeout="30">
  </forms>
</authentication>

or you can check your session as the following

if(Session["your_key"] != null)
{
   //Session is not expired
}
else
{
   //Session is expired
}

You can also use this way to detect session has expired or not.

protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        //This means session was timed out and new Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }
Close