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

- Pranay on Jul 08 '15
- viewed 14204 times

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.

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;
     }
    
  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);
        }
    }
    

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

About the author

Pranay Deegoju
Sitecore Certified Professional

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



Leave your comments on this post here


SIGN UP AND GET LATEST UPDATES.

Recent Posts

×

Liked this article?

Subscribe with your email and get updates when ever a new article is posted.

By subscribing you agree to our privacy terms. We promise that we do not sell your data.