Technical & Miscellaneous Ramblings
RSS icon Email icon Home icon
  • Redirect user when session timeout

    Posted on July 15th, 2009 Dhaneel No comments

    I was searching for a best way to redirect client when sessions timeout.Found few solutions but I liked this one.

    1. private void CheckSessionTimeout()
    2.     {
    3.         string msgSession = "Warning: Within next 3 minutes, if you do not do anything, " + " our system will redirect to the login page. Please save changed data.";
    4.         //time to remind, 3 minutes before session ends
    5.         int int_MilliSecondsTimeReminder = (this.Session.Timeout * 60000) - 3 * 60000;
    6.         //time to redirect, 5 milliseconds before session ends
    7.         int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 5;
    8.  
    9.         string str_Script = @"
    10.            var myTimeReminder, myTimeOut;
    11.            clearTimeout(myTimeReminder);
    12.            clearTimeout(myTimeOut); " +
    13.                 "var sessionTimeReminder = " +
    14.             int_MilliSecondsTimeReminder.ToString() + "; " +
    15.                 "var sessionTimeout = " + int_MilliSecondsTimeOut.ToString() + ";" +
    16.                 "function doReminder(){ alert(’" + msgSession + "’); }" +
    17.                 "function doRedirect(){ window.location.href=window.location.href; }" + @"
    18.            myTimeReminder=setTimeout(’doReminder()’, sessionTimeReminder);
    19.            myTimeOut=setTimeout(’doRedirect()’, sessionTimeout); ";
    20.  
    21.         ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
    22.               "CheckSessionOut", str_Script, true);
    23.     }

    call this function on each page call. Like you can put it in

    1.  
    2. protected void Page_Load(object sender, EventArgs e)
    3.     {
    4.          this.CheckSessionTimeout();
    5.     }
    6.  

    Hope this will help.

    Leave a reply