views:

351

answers:

2

I'd like to create an administrative page to show that our use of session state isn't getting out of hand.

Is it possible to retrieve a list of all active sessions, and if so, how can I access all of the session data in each session?

A: 

Session's cant be accessed from another session. However by implementing membership provider you could know if a session is active and many other useful information about user's activities. Also by persisting the session state using a DB you could retrieve the information you want.

You could use an "active" flag to store/remove sessions in the db just to obtain a more scalable solution, in case that's important for you.

Raúl Roa
+3  A: 

Disclaimer: I just came up with this implementation because I thought this was an interesting - and solvable - problem. As such, there may be some issues or details I've neglected to consider. Nevertheless, if you are using InProc session state, here's a solution.

Summary: Create an Application-level object (eg. a List) stored in Application state created during the Application_Start event, and on each Session_Start event, add a reference to the session to your list. On Session_End, remove it. To retrieve all the active sessions and values, loop through your list of sessions, then through the session keys of each.

Global.asax

void Application_Start(object sender, EventArgs e) 
{
    Application["activeSessions"] = new System.Collections.Generic.List<HttpSessionState>();
}

void Session_Start(object sender, EventArgs e) 
{
    var activeSessions = (System.Collections.Generic.List<HttpSessionState>)Application["activeSessions"];
    activeSessions.Add(this.Session);
}

void Session_End(object sender, EventArgs e) 
{
    var activeSessions = (System.Collections.Generic.List<HttpSessionState>)Application["activeSessions"];
    activeSessions.Remove(this.Session);
}

SomePage.aspx

    //add something to session for test
    this.Session["someStr"] = DateTime.Now.ToString();

    //get sessions
    var activeSessions = (List<HttpSessionState>)Application["activeSessions"];
    foreach (var session in activeSessions)
    {
        Response.Write("Session " + session.SessionID + "<br/>");
        foreach (string key in session.Keys)
        {
            Response.Write(key + " : " + session[key] + "<br/>");
        }
        Response.Write("<hr/>");
    }

Output: (after loading up a second browser to hit the page)

Session sj0sa255uizwlu45zivyfg2m 
someStr : 8/28/2009 11:03:37 AM
----
Session 530b3sjtea22jm451p15u355 
someStr : 8/28/2009 11:03:43 AM
----
Kurt Schindler
So, basically, what you've done is implemented your own session server ;) As you say, this will work for InProc sessions - if you're not using InProc, then Session_End isn't called, but then you're storing all the session data in a database, so you could easily go and read it from there ;)
Zhaph - Ben Duguid