How can I view everything in Session State for all active Sessions?

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?

Asked on April 7, 2016 in ASP.NET.
Add Comment
1 Answer(s)

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
----
Answered on April 7, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.