how to count number of visitors for website in asp.net c#

Application State is volatile. Check the this MSDN articule:

When using application state, you must be aware of the following important considerations:

  • ...

  • Volatility Because application state is stored in server memory, it is lost whenever the application is stopped or restarted. For example, if the Web.config file is changed, the application is restarted and all application state is lost unless application state values have been written to a non-volatile storage medium such as a database.

So you should not use that for saving this kind of data that you want to persist over time. Because applications pools get reseted from time to time. And I suspect you don't want to reset your visitor count when that happens.

You'll need some kind of data store which can persist your data when you application is not running.

Here are some choices:

  • File (XML, JSON, plain text, etc.): sample xml code for visitors counter
  • Database (SQL Server, SQLite, etc.): sample database code for hit counter

In global.asax file under this method

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Application.Lock();
Application["NoOfVisitors"] = (int)Application["NoOfVisitors"] + 1;
Application.UnLock();
}

then in your page load please add

lblCount.Text = Application["NoOfVisitors"].ToString();

then you can get the number of visitors on your site .

Tags:

C#

Asp.Net

Global