Friday, October 19, 2007

Session_End and SessionState mode="SQLServer"

Submit this story to DotNetKicks

A webapp I'm working on now needs to keep track of the number of logged in users at any time. We used to rely on Session_End for deleting sessions. However, this turned out to work only if the SessionState mode was set to InProc.  For other scenarios, Session_End is simply not called. Ever.

So we programmed a background service that polls the database now and then, and deletes from our table the rows that don't exist in the AspState-database (AspState obviously keeps track of timed out sessions and removes them from the table). Clean and simple solution.

2 comments:

Kap said...

Hi,

We need to do exactily this but the problem that I am having is how do I know what user to set as offline.

In sql server, the records are deleted from the session state table every minute so you dont get access to the session information to deserialize it to get the userID of the person that you need to set offline.

Do you see what I mean? How did you solve this problem?

Stian Sveen said...

Hey,
I know exactly what you mean, we got to just the same issue. What we did is that when the user logs in, we record the userid and sessionid in a separate table - let's call it SessionUser.

Then you can compare the two tables and process the entries from the SessionUser table that don't exist in the aspnet table.

You should be aware that the SessionID in the aspnet table is not the same as the SessionID you get from the Session-object, so make sure you check the correct substring to get a match.

Good luck!