C# – Iterate through existing Session objects

asp.netasp.net-2.0c#-2.0

I want to be able to kill existing sessions for the same username when someone logs in to prevent multiple people from using the same login.

Is there a way to iterate through existing sessions and kill them?

Best Answer

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);
}

Now you can iterate through your sessions like this

var sessions = (List<HttpSessionState>)Application["sessions"];

foreach (var session in sessions)
       ...

In order to kill other sessions in you could check in the Session_Start method for the old session abandon it. That 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);
}