How to get the accurate total visitors count in ASP.NET
asp.net, c#, c#-2.0
Solution
You can never get an entirely accurate number: there is no way to (reliably) detect that a user "has navigated to another site" (and left yours) or that that user "closed the browser".
The Session_Start/Session_End way has the problem that Session_End is only called for "InProc" sessions, not if the sessions are stored in StateServer or SqlServer.
What you might be able to do:
- Hold a `Dictionary<string, DateTime>` in Application scope. This stored session-id's (the string key) against the time of latest access (the DateTime value)
- For each request with a valid session, find the session entry in the dictionary and update it's latest-access time (add a new entry if not found)
- When you want to get the number of online users, first loop through all entries in the dictionary and remove items where the session timeout has passed. The remaining count is the number of online users.
One problem (at least): if one user uses two browsers simultaneously, he has two sessions open and is counted double. If users always log in, maybe you could count on login-id instead of session-id.
Problem
I want to know the number of visitors online on my site. I did my research and found two solutions. Source: Code Project Online active users counter in ASP.NET It is easy to setup and easy to use but it increases the user count for every Ajax request/response too. My home page alone has 12 Ajax requests(8 requests to one page and 4 requests to another page). This dramatically increases the user count. Source: Stack Overflow Q/A Count the no of Visitors This one works exactly the same as the previous one. Source: ASP.Net Forum How to see "who is online" using C# This one looks better than the previous two. Here is the detail code of this solution. ``` void Application_Start(object sender, EventArgs e) { // Code that runs on application startup HttpContext.Current.Application["visitors_online"] = 0; } void Session_Start(object sender, EventArgs e) { Session.Timeout = 20; //'20 minute timeout HttpContext.Current.Application.Lock(); Application["visitors_online"] = Convert.ToInt64(HttpContext.Current.Application["visitors_online"]) + 1; HttpContext.Current.Application.UnLock(); } void Session_End(object sender, EventArgs e) { HttpContext.Current.Application.Lock(); Application["visitors_online"] = Convert.ToInt64(HttpContext.Current.Application["visitors_online"]) - 1; HttpContext.Current.Application.UnLock(); } ``` It seems to be able to ignore the increasing the count for every Ajax response but it still adds up for each page refresh or page request. Is there any approach to count the accurate number of online visitors in ASP.Net?