To Keep Track of Users - Hit Counter

In this article, we will see that how we can implement a simple counter using ASP.NET MVC


How To Make A Counter In Your Site Using ASP.NET MVC


A very simple and easy way of making a hit counter is by using Application State. Application State is stored in memory on the server and is faster than storing and retrieving information in a database.


We used Session variables instead of storing client IP address.


Step 1 : Create an ASP.NET MVC website and write the below code in Global.asax file.


protected void Session_Start(Object sender, EventArgs e)
{
    int temp = 0;
    if (Application["TOTALUSERS"] == null)
        Application["TOTALUSERS"] = 0;
    Application["TOTALUSERS"] = Convert.ToInt32(Application["TOTALUSERS"]) + 1;
    temp = Convert.ToInt32(Application["TOTALUSERS"]);

}

The problem using this approach is that if the application restarts, all the count in Application variable will be lost.


If you want to show the total visitors count on all the pages then use the following code snippet in the Layout.cshtml file.


<a>Total Number of Visitors : @ApplicationInstance.Application["TOTALUSERS"]</a>

Example

This example demonstrate how to create a hit counter that keeps track of the current and total number of users to your site


As you can see below, you'll need to add some code to the Application_Start event and the Session_End event that is also defined in the Global.asax file.


protected void Application_Start()
{
	Application["TOTALUSERS"] = 0;
	Application["ONLINEUSERS"] = 0;

}

protected void Session_Start(Object sender, EventArgs e)
{
	int onlineUsers = Convert.ToInt32(Application["ONLINEUSERS"]);
	onlineUsers++;
	Application["ONLINEUSERS"] = onlineUsers;

	int toplamUsers = Convert.ToInt32(Application["TOTALUSERS"]);
	toplamUsers++;
	Application["TOTALUSERS"] = toplamUsers;
}

protected void Session_End(Object sender, EventArgs e)
{
	int onlineUsers = Convert.ToInt32(Application["ONLINEUSERS"]);
	onlineUsers--;
	Application["ONLINEUSERS"] = onlineUsers;
}

<p>@ApplicationInstance.Application["TOTALUSERS"]</p>
<p>@ApplicationInstance.Application["ONLINEUSERS"]</p>

tag : Hit Counter ASP.NET MVC 5