views:

1070

answers:

4

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

A: 

To the best of my knowledge, with standard in-memory sessions you cannot. This is something I was grappling with last week and I came to the determination that it isn't possible unless you are using a session state server. Seems rather odd from a design standpoint if you ask me. :/

Nathan Taylor
A: 

Try the following code

 for (int i = 0; i < Session.Keys.Count - 1; i++)
        {
            Label1.Text += Session.Keys.Get(i) + " - " + Session[i].ToString()+"<br/>";
        }
Himadri
That's an iteration across the current session's keys. I want to iterate and display data from *all* sessions currently active within the server's session state.
Alex
+5  A: 

Iterating through all sessions will be probably not very thread-safe. But you can collect informations about sessions in global.asax evets Session_Start and Session_End:

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

 public static List<string> Sessions
 {
            get
            {
                lock (padlock)
                {
                    if (_sessionInfo == null)
                    {
                        _sessionInfo = new List<string>();
                    }
                    return _sessionInfo;
                }
            }
  }

        protected void Session_Start(object sender, EventArgs e)
        {
            Sessions.Add(Session.SessionID);
        }
        protected void Session_End(object sender, EventArgs e)
        {
            Sessions.Remove(Session.SessionID);
        }
Jan Remunda
A: 

On session start, add the session obj to a List in the global class. (Global.asax or Global.cs/vb)

powderllama