Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of all active sessions in ASP.NET

I know what user is logged in with the following line of code:

Session["loggedInUserId"] = userId;

The question I have is how do I know what users are logged in so that other users can see what users are currently logged in.

In other words can I get all "loggedInUserId" sessions that are active?

like image 300
hhh3112 Avatar asked Jan 13 '12 16:01

hhh3112


1 Answers

I didn't try rangitatanz solution, but I used another method and it worked just fine for me.

private List<String> getOnlineUsers()
    {
        List<String> activeSessions = new List<String>();
        object obj = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null, null);
        object[] obj2 = (object[])obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
        for (int i = 0; i < obj2.Length; i++)
        {
            Hashtable c2 = (Hashtable)obj2[i].GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj2[i]);
            foreach (DictionaryEntry entry in c2)
            {
                object o1 = entry.Value.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entry.Value, null);
                if (o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState")
                {
                    SessionStateItemCollection sess = (SessionStateItemCollection)o1.GetType().GetField("_sessionItems", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(o1);
                    if (sess != null)
                    {
                        if (sess["loggedInUserId"] != null)
                        {
                            activeSessions.Add(sess["loggedInUserId"].ToString());
                        }
                    }
                }
            }
        }
        return activeSessions;
    }
like image 106
hhh3112 Avatar answered Sep 19 '22 09:09

hhh3112