Tuesday, 26 June 2012

Show Online Users/Visitors in ASP.Net website

There are many ways to show online users/visitors in asp.net website.

Step:1 First, we need to add these lines in global.asax file

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["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
    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["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;

This will show that whenever distinct visitors opens our website in different browsers, and new session is created for him, our Online Users variable is increased in the global HttpApplicationState.

And when user closed browsers and does not click on any links then session will expires and Online Users variable is decreased.

Step:2 We need to enable SessionState and configure its mode also. To do that need to add these lines in web.config

    <sessionState mode="InProc" cookieless="false" timeout="20" />
  • In Proc mode stores session state value and variable in memory on the local web server. This mode is the only that supports Session_End event.
  • Timeout value (i.e in minutes) configure how long our sessions are kept alive. In this example, Timeout is set to 20 minutes that means, when the user click on some link on our website at least one time in 20 minutes, then users is considered as online but if they do not open any page or click on any link in 20 minutes then they are considered as offline.

So now we are done with the configuration steps. To show the number of online users/visitors, add these line in your aspx page

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


  1. I have created a web application and was wondering how to track visitors..... This one helped,,,

  2. Looking very interesting article with wonderful information
    Now I am able to learn ASP.NET on my own.
    Thank you for giving such a nice info
    plz do keep sharing on...