Search code examples
c#session-timeoutexpired-sessions

How to set a correct session expired for my code?


I have a code that doing the popup message for the session expired, as following. However, this code cannot do a correct counting session. When run the program, it will direct popup the session expired message which didn't follow the time that I had set. I know that why my message will popup so early because in my

Page.ClientScript.RegisterStartupScript(cstype, csname, strconfirm, false);

I didn't add in the "timeout" so it is not executed as I want, but how to add it? when I try to add it in, it will result as input format error. Can someone assist me for this problem?

string csname = "timeoutWarning";
Type cstype = this.GetType();
if (!Page.ClientScript.IsStartupScriptRegistered(cstype, csname))
{
    var timeout = HttpContext.Current.Session.Timeout * 60 * 1000;
    string strconfirm = "<script>if(!window.confirm('Your login session is about to expire. Do you want to extend it?')){window.location.href='../login.aspx'}</script>";
    Page.ClientScript.RegisterStartupScript(cstype, csname, strconfirm, false);
}

Solution

  • You are no where setting the timeout! Extract your java script code to function say SessionTimeOutHandler() and call that while sesssion expires:

     string strconfirm = "<script>" + 
                         "window.setTimeout('SessionTimeOutHandler()', 60000);" + 
    "function SessionTimeOutHandler() { "+
    "    if(!window.confirm('Your login session is about to expire. Do you want to extend it?'))"
    +"   {window.location.href='../login.aspx'}</script>"; }";
    

    Now, just replace your strconfirm initialization statement. It should work for you!