Track current users on ASP.NET MVC Application

If you have an MVC application you might want to have a mechanism to track the list of current users connected to your application.

Is it possible?

I found an interested solution on the http://graysoft.blogspot.com/2009/02/howto-get-current-online-users-count.html and I am just reposting it here because that page is sometimes offline.

The idea is simple. With an HTTPModule we connect to the session_start event and keep a list of online users.

To add this module just modify the web.config file:

    <modules runAllManagedModulesForAllRequests="true">
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule" />
      <add name="UserTracking" type="UpgradeHelpers.WebMap.Server.OnlineUsersModule"/>
    </modules>

A simple page to view the current users will be something like:

Controller

using System.Web.Mvc;

namespace UpgradeHelpers.WebMap.Server  
{
    [SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]
    public class OnlineUsersController : Controller
    {
        public ActionResult Index()
        {

            return View();
        }

    }

}

And the view:

@{
    Layout = null;
}
<html>

<body>  
@{
    var currentUsers = UpgradeHelpers.WebMap.Server.OnlineUsersModule.OnlineUsers;
}
    <h1>Current Online Users</h1>
    <ul>
        @foreach (var user in currentUsers)
        {
            <li>@user.ToString()</li>
        }
    </ul>

</body>


</html>  

This will give an output like: