Hi,
how to get list of all active ASP.NET Sessionsid
Hi,
how to get list of all active ASP.NET Sessionsid
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Naimish MakwanaRank #324 · 7.7K reputationPosted Sep 3, 2024, 8:53 AM EDT
To get a list of all active ASP.NET Session IDs, you can use a combination of code in your
Global.asaxfile and some reflection. Here’s a basic example:Global.asax:public class Global : System.Web.HttpApplication { private static readonly List _sessions = new List(); private static readonly object padlock = new object(); public static List 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); } } }public static IEnumerable GetActiveSessions() { var sessions = new List(); var obj = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null, null); var obj2 = (object[])obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj); foreach (var cache in obj2) { var c2 = (Hashtable)cache.GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(cache); foreach (DictionaryEntry entry in c2) { var o1 = entry.Value.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entry.Value, null); if (o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState") { var sessionId = (string)o1.GetType().GetField("_sessionId", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(o1); sessions.Add(sessionId); } } } return sessions; }This approach works for InProc session state mode. If you’re using StateServer or SQLServer modes, you’ll need a different approach as
Session_Endwon’t be triggered12.Thanks