Hello I am creating a basic counter that adds +1 everytime someone accesses the website. The problem is it adds 1 everytime someone goes to another page on the site, not when the person goes to the site for the first time, making the data very inaccurate (ex. One user that accesses the site may go to 8 diff开发者_开发技巧erent pages, therefore adding 8 to the counter, insead of 1). Is there a way to detect when a user is accessing the site on the first initial load?
I'm using asp.net 3.5 in C#.
Try using the Session_Start event in Global.asax.cs
protected void Session_Start(object sender, EventArgs e)
{
//Increment your counter here
}
This will add one to the counter for each user, the first time they hit a page on your site. Then, once the browser session has timed out (by default 20 minutes of inactivity on your site), another increment will occur the next time the hit your site. The timeout period is configurable.
If you want to do it for the first time they EVER hit your site, then the cookie approach mentioned by some other posters will do this. But remember, you have no way of knowing whether it is the same user, just the same computer - think Internet cafe.
Edit: Following your comment about anonymous users: What are your authorizatioin settings? e.g.
<!-- Allow access to anonymous (unauthenticated) users. -->
<authorization>
//probably shouldn't do this in particular, but you might want to look at your settings
<allow users="*" />
</authorization>
Set a cookie. Check for the cookie, if it's present, then don't increment the count.
If the user is required to login, you could count how many times they login.
You don't want to log by IP Address alone, because anyone behind a firewall is going to show up as the same IP Address.
I think cookies are the way to go here. When a user first goes to your site, set a cookie. For any request after that, only increment your counter if the cookie is not present. Using Session_Start will give you similar behavior, but Session cookies expiration may lead you to track the same person multiple times.
If you could expand on what the purpose of the counter is, it would help in determining the proper solution.
Store the IP address of all visitors, but only store unique IP addresses.
Use Google Analytics. Very comprehensive tracking of your users, free (to a degree).
精彩评论