Create a Hit Counter Using the Global.asax File in ASP.NET




You can place the below code in Global.asax file and you need to call that variable in the aspx page. Example:

Global.asax Code

     void Application_Start(object sender, EventArgs e)
        { 
            Application["TotalHitCount"] = 0;
        }

Not required to put anything in other events in this file if you want to test while Page loading.Keep the below code on Page_Load() like below and press F5 to test it.

Code Behind

protected void Page_Load(object sender, EventArgs e)
        {
            Application["TotalHitCount"] = Convert.ToInt32(Application["TotalHitCount"]) + 1;
            lblTotCount.Text = Application["TotalHitCount"].ToString();
        }


Otherwise you can use like below in place of Page_Load(), 

Alternative Procedure

void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            Application.Lock();
            Application["TotalHitCount"] = Convert.ToInt32(Application["TotalHitCount"]) + 1;
            Application.UnLock();
        }
        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends.
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer
            // or SQLServer, the event is not raised.
            Application["TotalHitCount"] = Convert.ToInt32(Application["TotalHitCount"]) - 1;
        }


Show or use it as per your application's requirement.

No comments:

Post a Comment