How can I determine the number of users on an ASP.NET site (IIS)? And their info?

Samuel Meacham picture Samuel Meacham · Oct 1, 2008 · Viewed 33.2k times · Source

Is there a way to determine the number of users that have active sessions in an ASP.NET application? I have an admin/tools page in a particular application, and I would like to display info regarding all open sessions, such as the number of sessions, and perhaps the requesting machines' addresses, or other credential information for each user.

Answer

Eduardo Molteni picture Eduardo Molteni · Mar 18, 2009

In global.aspx

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    Application["OnlineUsers"] = 0;
}

void Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
    Application.UnLock();
}

void Session_End(object sender, EventArgs e)
{
    // Code that runs when a session ends. 
    // Note: The Session_End event is raised only when the sessionstate 
    // mode is set to InProc in the Web.config file. 
    // If session mode is set to StateServer or SQLServer, 
    // the event is not raised.
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
    Application.UnLock();
}

Note: The Application.Lock and Application.Unlock methods are used to prevent multiple threads from changing this variable at the same time.

In Web.config

Verify that the SessionState is "InProc" for this to work

    <system.web>
        <sessionState mode="InProc" cookieless="false" timeout="20" />
    </system.web>

In your .aspx file

Visitors online: <%= Application["OnlineUsers"].ToString() %>

Note: Code was originally copied from http://www.aspdotnetfaq.com/Faq/How-to-show-number-of-online-users-visitors-for-ASP-NET-website.aspx (link no longer active)