views:

390

answers:

4

I would like to have the session state in a separate process for my app, but I would also like to have some code run whenever a user's session is over. (changing a status string that indicates whether they are online or not and decrementing the online users count.)

If my session state is InProc in the web config, I can use the Session_End method to run this code, but how do I do this if not?

+1  A: 

Are you using SQL State or are you using IIS State Server Service?

If you're using SQL State, you can just do a check on the userID. When the session times out, the row is removed and that's that.

If you're using IIS State Server Service there is no direct method of executing code on Session_End or anything similar. Sorry.

Jonathan
+1  A: 

There is a bit of an uncertainty principle in trying to detect when a session has expired. By querying the server to see if it is alive (using AJAX or similar), you are actually keeping it alive, which is usually the exact opposite behavior that you want.

I usually do this by embedding javascript code in the page. :

var sessionTimeout = 20; //minutes - set this programmatically server-side based on your configured timout interval
setTimeout('timeoutAlert()', (sessionTimeout + 1) * 1000 * 60); //we add one minute buffer because this is an inaccurate process and we want to make sure they are actually timed out before we attempt to redirect
function timeoutAlert()
{
    alert("Your sesssion has ended, you will now be redirect to the login page.");
    document.location = '/home.aspx';
}

Note this timeoutAlert() can modify some HTML client-side, run some AJAX to execute code server-side, whatever you need it to do. You will have to be careful to cancel and reset the setTimeout if you make any calls to the server (e.g., via AJAX) after the page is rendered.

RedFilter
A: 

If you are using SQL Server, Then you could modify the DeleteExpiredSessions stored procedure to do your work (i.e. decrement online users).

alternatively, you can check a session variable on each page load, if it comes back null then the session has ended.

You can also put a javascript check to see if the browser has closed or, if the logout button has been clicked, etc... then make an ajax call to manually close the session.

Russ Bradberry
+1  A: 

You cannot assign an event handler that will always run when a session ends. There are approximations, such as assigning an event handler to an InProc session's End event (which will only be run if the session ends normally), or altering the DeleteExpiredSessions proc for a SQL Server session.

Justice