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

Pranay
Aug 30, 2020  ·  33777 views

This hit counter is used to track/count the number of users visited a particular page in your website. The implementation in the below tutorial uses C# and asp.net Mvc sessions. Same logic can be applied to websites developed in java or any other languages with few changes.

How it works?

  • 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. (Here, it is assumed that you have an entry in database tables for each webpage).
  • 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.

Hit counter

How to implement hit counter in mvc?

  1. Have a method which will be automatically called before every Action method.

    Every controller in mvc inherits the inbuilt ‘Controller’ class. So here, we will have a new Controller class called BaseController. This BaseController class also inherits the in built Controller class. All the controller in the website can inherit BaseController instead of Controller class.

    Inside the BaseController class we will override the Initialize method, then trigger the base class initialize method. If you are confused don’t worry :) :). Have a look at the below code (BaseController.cs). It will be simple.

    namespace Namespace.Controllers
    {
        public abstract class BaseController : Controller
        {
            protected override void Initialize(System.Web.Routing.RequestContext requestContext)
            {
                //Our code goes here
                //Our code goes here
                //Our code goes here
                //Our code goes here
                //Our code goes here
                //Have this line to call base class initialize method.	
    
                base.Initialize(requestContext);
            }
        }
    }
    

    All the other controllers in the website can inherit BaseController instead of Controller as shown below.

    namespace KewlCodes.Controllers
    {
        public class PostsController : BaseController 
        {
        //action methods
        //action methods
        //action methods
         }
    }
    

    Note: only if its controller inherits the BaseController, our new initialize method will be called before executing the action methods.

  2. Inside this method, initiate a session if it is not done already and check if the user has visited this page already.

    int UrlId = getCurrenPageId();
    //check if the user opening the site for the first time 
    if (requestContext.HttpContext.Session["URLHistory"] != null)
    {
        //The session variable exists. So the user has already visited this site and sessions is still alive. Check if this page is already visited by the user
        List<int> HistoryURLs = (List<int>)requestContext.HttpContext.Session["URLHistory"];
        if (HistoryURLs.Exists((element => element == UrlId)))
        {
              //If the user has already visited this page in this session, then we can ignore this visit. No need to update the counter.
              requestContext.HttpContext.Session["VisitedURL"] = 0;
        }
        else
        {
           //if the user is visting this page for the first time in this session, then count this visit and also add this page to the list of visited pages(URLHistory variable)
              HistoryURLs.Add(UrlId);
              requestContext.HttpContext.Session["URLHistory"] = HistoryURLs;
    
        	  //Make a note of the page Id to update the database later 
              requestContext.HttpContext.Session["VisitedURL"] = UrlId;
         }
    }
    else
    {
            //if there is no session variable already created, then the user is visiting this page for the first time in this session. Then create a session variable and take the count of the page Id
            List<int> HistoryURLs = new List<int>();
            HistoryURLs.Add(UrlId);
            requestContext.HttpContext.Session["URLHistory"] = HistoryURLs;
            requestContext.HttpContext.Session["VisitedURL"] = UrlId;
     }
    

    Note:

    • The method getCurrenPageId() returns a unique number of the current page from the URL. For example if you see the URL on this page, there is a number 1135 which is a unique id of the page. Same is with even StackOverflow site if you observe. So based on the site URL structure the implementation of this method may differ.
  3. Update the counter if required and save it to database

    Now in the action method, which loads the page, check the page id session variable and update the database. Below is the sample code.

    //Update page views
    int PageId;
    if (int.TryParse(HttpContext.Session["VisitedURL"].ToString(), out PageId))
    {
        if(PagetId > 0)
        {
           UpdatePageViews(PagetId);
        }
    }
    

    Note:

    • The method UpdatePageViews() will just increment the views count for that page id (1135 in my case) in the database table. Based on the table structure, the implementation of this method would also defer.

Please share or comment if you found it useful!!!!

AUTHOR

Pranay

A Software Engineer by profession, a part time blogger and an enthusiast programmer. You can find more about me here.


Post a comment




Thank you! You are now subscribed.

Sign up for our newsletter

Subscribe to receive updates on our latest posts.

Thank you! You are now subscribed.