Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hit counter for MVC ASP.NET website

Tags:

c#

asp.net-mvc

How to create a hit counter(visitor counter) for each page in MVC website? And store information in MS SQL Database. The same as stackoverflow using on each page.

Please show me an example. Thank u

like image 611
Andrew Fales Avatar asked Nov 05 '22 03:11

Andrew Fales


2 Answers

I was able to do this using Session variables, sql server db in ASP.NET MVC.

Note: I used session variables instead of storing client IP address. As saving all the client address will overflow your database. This works similar to the Stackoverflow pages viewed property showing for every question at the top right.

This is how it worked for me.

Whenever a user opens a particular web page in your website, the counter increments and the updated count will be updated in sql server database(it could be anyother database) tables. If the same user visits the same webpage again within the same session, the counter will not be incrmented. That means if user refreshes a web page multiple times with in the same session, the counter will not be incremented, as it is a single visit by that user. If the same visitor closes his session(say he closes the browser) and reopens the same web page the counter will be incremented considering it as a separate visit. Here are the steps I followed to implement it.

Have a method which will be automatically called before every Action method. Inside this method, initiate a session if it is not done already and check if the user has visited this page already. Now, update the counter variable accordingly and save the count to db if required. Here is the complete procedure I have followed. Hope it helps.

Source: Count number of visitors of a page in asp.net mvc (HIT counter)

like image 38
Pranay Avatar answered Nov 09 '22 09:11

Pranay


In your master page insert a function call that logs the name of the page or whatever other details you want. Run your counts and there you go.

like image 187
Matt Avatar answered Nov 09 '22 08:11

Matt