Wednesday, 24 September 2014

Asp.net Counting Number of hits to the Page

Suppose You have 2 pages in Web application and you want to count the number of hits to your page, how can you achieve this ? 

1: You should have different counters for each page, and store these counters in Application cache to be at the web application level;

2.In the Global.asax.cs init your used counter for each page like in the next example:


void Application_Start(object sender, EventArgs e)
{
   Application["Page1Counter"] = 0;
   Application["Page2Counter"] = 0;
   //...
}


2.The logic for incrementing the counters for each page should be in the Page_Load event handler like in the next example:

protected void Page1_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)   
    {
       int counter = (int)Application["Page1Counter"];//Get from the cache!
       counter++;
       Application["Page1Counter"] = counter; //Cache the result back!
    }
    //....
}

3.Example for your new question regarding only one page and multiple users:

protected void Page1_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)   
    {
       string userID = User.Identity.Name; //Get the user ID!
       string key = string.Format("Page1CounterForUser{0}", userID);//Create the key for current user!
       int counter = (int)Application[key];//Get from the cache!
       counter++;
       Application[key] = counter; //Cache the result back!
    }
    //....
}



No comments:

Post a Comment