Alert on Session Timeout in ASP.Net

Tags: asp.net, web | Comments (2) | Posted on Saturday 10th of October 2009 03:08:00 PM

Why

You must have seen this before, you left your online banking open for a while and then suddenly a pop up comes up telling you, "Hey your session is about to run out!"
This message helps the user keep their session alive so that they do not get logged out.

How

The session timeout can be changed in your web config

    
...
The value 60 here represents 60 minutes.
So after 60 minutes inactivity from the user, the session will expire. We can't just send a message from the server on that event to the user but we can make an assumption of when that timeout might happen on the client.
We will assume that the timer resets every time the user
  1. Goes to another page
  2. Makes an Ajax Postback
  3. Makes a Callback
And with that note I give you the following script
var timeOut = 60 * 60 * 1000; // minutes * seconds * millseconds
var timer = null;
var reset = function()
{
   if (timer) clearTimeout(timer);
   timer = setTimeout(function() { window.onbeforeunload=null; window.location = "/TimeOut.aspx"; }, timeOut);
};
reset();

if (Sys) Sys.Application.add_load(reset); // If Ajax Client Library available, apply reset on postback
var orig = WebForm_DoCallback; /// Hijack the callback function to allow us to know when a callback is made, callbacks reset the session timer!
WebForm_DoCallback = function() {reset(); orig.apply(this, arguments); };
After 60 minutes of inactivity, the script will redirect the user to the "TimeOut.aspx" page to let them know that their session has expired.
But it would be lot nicer to let the user keep their session alive, so just set the timer to something less then the actual timeout time such as 50 minutes and then give the user the option to keep their session alive. And if the user chooses to do so just do a Callback/Postback to reset the timeout.

This looks like good stuff. As far as the timeout, does this integrate with the Forms Authentication Timout attribute? Or do I have to set SESSIONSTATE as well?
John Bailo on Tuesday 15th of December 2009 12:40:16 PM
I looked it up and apparently Session timeout and Authentication timeout are seperate attributes. So yes, you have to set the SESSIONSTATE as well.
Shah Pavel Jamal on Tuesday 15th of December 2009 10:01:07 PM
Click here to add your own comment!