List all active ASP.NET Sessions

Alex picture Alex · Sep 24, 2009 · Viewed 62.5k times · Source

How can I list (and iterate through) all current ASP.NET sessions?

Answer

Jan Remunda picture Jan Remunda · Sep 24, 2009

You can collect data about sessions in global.asax events Session_Start and Session_End (only in in-proc settings):

private static readonly List<string> _sessions = new List<string>();
private static readonly object padlock = new object();

 public static List<string> Sessions
 {
       get
       {
            return _sessions;
       }
  }

  protected void Session_Start(object sender, EventArgs e)
  {
      lock (padlock)
      {
          _sessions.Add(Session.SessionID);
      }
  }
  protected void Session_End(object sender, EventArgs e)
  {
      lock (padlock)
      {
          _sessions.Remove(Session.SessionID);
      }
  }

You should consider use some of concurrent collections to lower the synchronization overhead. ConcurrentBag or ConcurrentDictionary. Or ImmutableList

https://msdn.microsoft.com/en-us/library/dd997373(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/dn467185.aspx