Iterating through existing session objects
Add this to your global.asax
protected void Application_Start(object sender, EventArgs e)
{
Application["sessions"] = new List<HttpSessionState>();
}
protected void Session_Start(object sender, EventArgs e)
{
var sessions = (List<HttpSessionState>)Application["sessions"];
sessions.Add(this.Session);
}
protected void Session_End(object sender, EventArgs e)
{
var sessions = (List<HttpSessionState>)Application["sessions"];
sessions.Remove(this.Session);
}
You can now iterate through your sessions like this
var sessions = (List<HttpSessionState>)Application["sessions"];
foreach (var session in sessions)
...
To kill other sessions, you can check the method Session_Start
so that the old session discards it. It might look something like this.
protected void Session_Start(object sender, EventArgs e)
{
var userId = (int)this.Session["userId"];
foreach (var session in sessions)
if ((int)session["userId"] == userId)
session.Abandon();
var sessions = (List<HttpSessionState>)Application["sessions"];
sessions.Add(this.Session);
}
source to share
Once I implemented this, I stored the user ids (or something unique) in an application variable, in a dictionary, or in an array. Easily check for the presence of a user ID in the application dictionary at login time. The only real problem is people who don't log out and just close the browser. You will never find a reliable way to detect this event.
source to share
Turn off the cuff:
In Session_Start (usually a successful login), in the store UserID of the user and SessionID in the lookup table (or a new column in the user table).
In each request, you will need to check that the UserID (stored in the session) and SessionID match the values stored in the Lookup table as an authentication step.
source to share