Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Session timeout in ASP.NET is such an important problem with web developer. When session ends, we run into some exceptional situations. There are also many solutions to deal with this problem on the Internet. But few of them have discussed about redirecting to another page when there is session timeout, especially when we work with Ajax UpdatePanel.

So, I suggest a way to do this.

Solution

My main idea is: 3 minutes before session is gone, we will alert the user to save his/her data or make any postbacks. If user still does not do anything, then 5 milliseconds before session goes, we will redirect the page to Login.aspx (or just refresh page by redirecting to itself).

Using the Code

Add the following code to your Master page:

private void CheckSessionTimeout()
{
    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.';
    //time to remind, 3 minutes before session ends
    int int_MilliSecondsTimeReminder = (this.Session.Timeout * 60000) - 3 * 60000; 
    //time to redirect, 5 milliseconds before session ends
    int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 5; 

    string str_Script = @"
            var myTimeReminder, myTimeOut; 
            clearTimeout(myTimeReminder); 
            clearTimeout(myTimeOut); " +
            "var sessionTimeReminder = " + 
		int_MilliSecondsTimeReminder.ToString() + "; " +
            "var sessionTimeout = " + int_MilliSecondsTimeOut.ToString() + ";" +
            "function doReminder(){ alert('" + msgSession + "'); }" +
            "function doRedirect(){ window.location.href='login.aspx'; }" + @"
            myTimeReminder=setTimeout('doReminder()', sessionTimeReminder); 
            myTimeOut=setTimeout('doRedirect()', sessionTimeout); ";

     ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), 
           "CheckSessionOut", str_Script, true);
}
private void Page_Load(object sender, System.EventArgs e)
{
    this.CheckSessionTimeout();
}

If you do not want to redirect to login page, you can just refresh the page by replacing it by this code:

function doRedirect(){ window.location.href=window.location.href; }

If you do not use ScriptManager, you can replace with Page.RegisterClientScriptBlock(...)

Hope this helps.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Questionhow to create secured login page
appusri5387
2:56 4 Nov '09  
how to disable browser's back n forward button after logged out? or how to expire a page when logged out?
GeneralHow to add session renew state to the alert box?
Robert H.
8:59 12 Aug '08  
I'm sure this is pretty easy to do but I'm javascript handicapped Smile How do we go about adding a function to the alert box so that when they click the 'Ok' button, it will auto refresh their session state for them. This way the user won't have to know that they need to click on something that does a post back to restart their session timer?

Also, I don't suppose it's possible to add a real-time timer count down to that alert box is it so the user knows exactly how much time remains? This way if the user wasn't at the screen when the box first appeared but sat down soon after, they would know exactly how much time was really left? Smile
GeneralRe: How to add session renew state to the alert box?
Nguyen Quy Minh
21:28 12 Aug '08  
Hi Robert,

If you want the page is refreshed after the user click 'OK' button, you just modify the javascript about like this: window.location.href = window.location.href (instead of window.location.href='login.aspx').

About the count-dount timer within the message box, you can search over the Internet to get the javascript code and modify it for your scenario. I think it is pretty easy Wink

Live free, die well!
http://www.sirvina.com

GeneralRe: How to add session renew state to the alert box?
Robert H.
10:31 13 Aug '08  
Thanks, I appreciate it Smile

I'll give it a shot and see how it works.

I did notice one strange thing though. Not sure how or why, but I noticed that if I left that 3 minute count down window open and I waited an easy 5 minutes before pressing "OK", instead of it already timing out (since there was only 3 minutes left), my session wasn't timed out at all... I did a post back to check and sure enough, the post back worked... any idea why this would be? since it's client side script, i can't see how the server would've gotten a postback to reset the timer... (i had the web.config session timeout set at 4 minutes for testing purposes).
GeneralRe: How to add session renew state to the alert box?
Nguyen Quy Minh
20:07 13 Aug '08  
Ok. It is really a strange.
When you implement this, you already renew the session too Smile

Live free, die well!
http://www.sirvina.com

GeneralRe: How to add session renew state to the alert box?
Robert H.
6:37 14 Aug '08  
Oh, well if that's the case than that explains why it didn't time out. cool, thanks for the help and the code! Smile Now maybe the users will stop griping about wanting a warning of a pending session expiration... hehe
GeneralRe: How to add session renew state to the alert box?
rcarroll
11:20 14 Jan '09  
What do you mean, renew the session too?

I am having the same problem. When the message pops up saying they will be logged off in three minutes, I don't hit the ok button (since this will be the most likely scenario in my project). I would assume that after 3 minutes, it would close that window and redirect to the login page. However, it doesn't do anything. Then, when I click the ok button, it times me out as it should.

Thanks in advance!

Rosemary
GeneralRe: How to add session renew state to the alert box?
ksalvage
4:52 15 Jan '09  
The alert box is a modal dialog in the browser so it could well be that the thread that the timer is running in is suspended while the alert is being displayed. I'm not sure how browsers treat timers running in the main context, or how the threading model works internally. A better solution would be to create a div that is hidden and show it when the time runs out.

I use the following code in my master page head:

<script language="javascript" type="text/javascript">
function doRefresh(){ javascript:__doPostBack(''); }//window.location.href=window.location.href; }

function doRedirect(){ window.location.href='login.aspx'; }

function getStyleObject(objectId) {
// checkW3C DOM, then MSIE 4, then NN 4.
if(document.getElementById && document.getElementById(objectId))
return document.getElementById(objectId).style;
else if (document.all && document.all(objectId))
return document.all(objectId).style;
else if (document.layers && document.layers[objectId])
return document.layers[objectId];
else
return false;
}

function setObjectVisibility(objectId, newVisibility) {
var styleObject = getStyleObject(objectId);
if (styleObject)
{
styleObject.visibility = newVisibility;
return true;
}
else
return false;
}

function showUserMessage()
{
setObjectVisibility("userMessage","visible");
}

function hideUserMessage()
{
setObjectVisibility("userMessage","hidden");
}
</script>

with a div that looks like this

<div id="userMessage" style="position: absolute; background-color: white; z-index: 1;
display: block; top: 5px; left: 20px; visibility:hidden; border: 1px solid black;"
>
<table width="400" style="width: 200px; height: auto;
background-color:white;"
>
<tr>
<td>
Warning: Within next 3 minutes, if you do not do anything, the system will redirect
to the login page. Please save changed data.
</td>
</tr>
<tr>
<td align="right"><asp:Button CssClass="groupButton" ID="btnStillHere" OnClientClick="doRefresh()" Text="OK" runat="server" /></td>
</tr>
</table>
</div>

and this in my code behind:

protected void Page_Load(object sender, EventArgs e)
{
CheckSessionTimeout();
}

private void CheckSessionTimeout()
{
//time to remind, 3 minutes before session end
int int_MilliSecondsTimeReminder = (Session.Timeout * 60000) - 3 * 60000;
//time to redirect, 5 miliseconds before session end
int int_MilliSecondsTimeOut = (Session.Timeout * 60000) - 5;

StringBuilder sb = new StringBuilder();
sb.AppendLine("<script language="\"javascript\"" type="\"text/javascript\"">");
sb.AppendLine("
var myTimeReminder, myTimeOut;");
sb.AppendLine("
clearTimeout(myTimeReminder);");
sb.AppendLine("
clearTimeout(myTimeOut);");
sb.AppendFormat("
var sessionTimeReminder = {0};\n", int_MilliSecondsTimeReminder);
sb.AppendFormat("
var sessionTimeout = {0};\n", int_MilliSecondsTimeOut);
sb.AppendLine("
myTimeReminder=setTimeout('showUserMessage()', sessionTimeReminder);");
sb.AppendLine("
myTimeOut=setTimeout('doRedirect()', sessionTimeout);");
sb.AppendLine("
</script>");
Page.RegisterClientScriptBlock("CheckSessionOut", sb.ToString());

}


This works well for me

Life is a game. Play to win

GeneralRe: How to add session renew state to the alert box?
Nguyen Quy Minh
18:54 16 Jan '09  
Thanks Ksalvage very much.
Your code with div alert works very great! Wink

Live free, die well!
http://www.sirvina.com

QuestionWorks fine but confirm box comes even when I am working on screen
chaggu
13:03 9 Jul '08  
Hi,
I implemented your code and it works fine but I got stuck with this problem:
Because I am registering this function with setTimeOut of reminder session time, I get the confirm box eventhough I am working on it. Suppose I have a timeout of 20 min. I am registering this code with Session.Timeout delay.
Even when I am working on the application, this function gets fired and I get the confirm box.

We are using sqlstate for storing sessions.

How can I avoid this confirm box to appear and make it appear when user has only 1 min left in the session?

Thanks in advance,
Chaggu.
AnswerRe: Works fine but confirm box comes even when I am working on screen
Nguyen Quy Minh
0:25 10 Jul '08  
You are working, but maybe you do not make any postbacks to server, so it still show message to confirm by the time session timeout.
During your session, if you make some postbacks, the message must NOT appear (because the time to remind has been reset!).

Live free, die well!
http://www.sirvina.com

QuestionRe: Works fine but confirm box comes even when I am working on screen
chaggu
4:22 10 Jul '08  
Thanks for your quick reply.

The problem is I have an application with single page and multiple tabs. I put this script register block in Page_load of that page. It doesnt get called even if a new tab is created or a postback happens in the tab.

Can you please suggest me something else, I would really appreciate?

Thanks,
Chaggu.
AnswerRe: Works fine but confirm box comes even when I am working on screen
Nguyen Quy Minh
7:12 11 Jul '08  
Hi, I think your tab control is not in the update panel. If you do not use update panel, you should try to replace ScriptManager.RegisterClientScriptBlock(...) with Page.RegisterClientScriptBlock(...) method Smile

Live free, die well!
http://www.sirvina.com

GeneralRe: Works fine but confirm box comes even when I am working on screen
chaggu
5:19 24 Jul '08  
I am using an Alert box instead of Confirm box and it works for my scenario.
Thanks for replying.
Thanks,
Chaggu.
GeneralMany thanks
tndang
4:14 4 Jul '08  
It works fine and save time for me.
Thanks.

tnd

GeneralNo effect when something happened in update panel.
StressBall
1:23 3 Jul '08  
Thanks for this article.

i just want to ask what could be wrong with my implementation because nothing is happening when i did something inside the update panel. the injected javascript code seem like its not taking in effect. I hope you can help me on this.

Thanks.
GeneralRe: No effect when something happened in update panel.
Nguyen Quy Minh
7:03 3 Jul '08  
Could you post something about your code?
Did you try to register javascript with ScriptManager.RegisterClientScriptBlock(...) method instead of Page.RegisterClientScriptBlock(...)?

Live free, die well!

GeneralRe: No effect when something happened in update panel.
StressBall
17:49 3 Jul '08  
i registered the javascript by user ScriptManager.RegisterClientScriptBlock

if i run the application and do nothing, after the set timeout, it works fine, it redirects to the page it set. but when i did something on the update panel, say, i populated a gridview, and do nothing after that, wait for the set timeout, nothing happened, as if the javascript code didn't took in effect. please help me on this.

Thanks
GeneralRe: No effect when something happened in update panel.
Nguyen Quy Minh
4:04 4 Jul '08  
Did you add the function generate javascript to PageLoad (without inside !Page.IsPostBack) yet? After gridview changed, it would call this function to re-generate again the javascript snippet. And it should work fine.

Live free, die well!
http://www.sirvina.com

GeneralRe: No effect when something happened in update panel.
anukit
4:48 24 Sep '08  
Hi, I am using rad ajax now i am having the same problem i.e when i do a operation in the grid and leave the operation the page does nort redirect on session timeout.I have take care of adding generate javascript functon to PageLoad?please help
GeneralSome more improvements...
Tuomas Hietanen
6:38 27 Jun '08  
If you don't use alert in doReminder()-function, but a hidden html-control (like span) you can include a link in the control to refresh the session (like do a postback, form.submit or load something).

Or if you have a javascript in your input-fields:
After doReminder()-time has passed the input-field javascript could set a flag that user have done some input near session expire time. Then you know that user is near and you can refresh the session just before it expires. A kinda like gmail saving the new message to draft.
GeneralRe: Some more improvements...
Nguyen Quy Minh
8:22 27 Jun '08  
Thanks for your improvments Smile

Live free, die well!

Generalthanks!
vegeta4ss
5:17 25 Jun '08  
I was looking for something like this just a few days ago. Now I have a good example.

Many thanks.
GeneralWhat if javascript is disabled?
evolved
9:04 19 Jun '08  
I think the easier solution is to use the META tag for refresh and set the url to go to a TimeOut.aspx page, I use this all over one of our portal websites, and it works great.
GeneralRe: What if javascript is disabled?
Nguyen Quy Minh
22:48 19 Jun '08  
If you don't use Ajax UpdatePanel in the page then the META tag refresh works great. But if the page contains UpdatePanel, it gets a problem. When the user made the postback, the META tag content does not refresh to get new time out for session (because META tag isn't inside any updatepanel). So it does not work correctly! Smile

Live free, die well!


Last Updated 18 Jun 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010