Reputation:
Is there a way to find out if a session Id is valid from within an existing request context? In that, if I'm given a session Id, and I'm currently in another session initiated by a Http Request and I'm on a page or in some class, can I validate that session Id, if it's valid and currently exists and hasn't been abandoned?
The reason for this is, we need to lock down the user login process on the page for the project I'm working on so that any user can only be logged in once. My thought on this was to add a session id column to the user table, if it's null, they're logged out, and it's set when they log in and cleared when they log out or on Session_End in global.asax. However, if for some reason a session is abandoned without clearing that, I need to be able to log them in again, and in that case whenever they log in and it finds a session Id in that column, I'm thinking it should somehow check to see if that Session Id is active and valid, if not, it'll reset it to their new session Id and allow them to log in.
Thanks
Upvotes: 6
Views: 4989
Reputation: 15413
Another option you have/had :-) would be to use WeakReferences :
Dictionary<youruseridtype,WeakReference>
is stored at application level as Application["mySessionDictionnary"]The WeakReference ensures that you will not suffer memory leaks.
NB : this would only work with inProc session management. As the Dictionnary would not survive an application restart, it should be the same for sessions.
Hope that you already found the right answer to your problem ;-)
Upvotes: 1
Reputation: 4389
The only way I can think is to do as Neperz says and store your sessions in a database using the SQLServer
session provider, meaning you can then use an SQL query to see what is available.
But there are some caveats to consider:
Session_End
event will never fire if using the SQLServer
session provider.Session.Abandon()
in your code to finish a session (e.g. when a user logs out), your sessions can hang around until an SQL Agent job cleans up any expired sessions. This means that if someone just closed their browser window then their session would still appear as "active" which may complicate your implementation.Upvotes: 1
Reputation: 31
You need to store sessions in database in order to find before.
See more in HOW TO: Configure SQL Server to Store ASP.NET Session State
Upvotes: 2
Reputation: 100547
There is no direct way of validating SessionId. Options:
Note: I would not use session Id for that purpose as you'll be relying on implementation details. Maybe simply rejecting sessions that do not look like latest for this user would work. Having "my current session name" property saved in Session["someName"]
and in user DB should be enough to reject rendering of older sessions.
Upvotes: 0