对于简单的实现,您可以使用自定义 HttpModule。对于您的应用程序的每个请求,您将:
- 检查 Request.Cookies 是否包含跟踪 Cookie
- 如果跟踪 cookie 不存在,这可能是新访问者(或者,他们的 cookie 已过期 - 参见 4。)
- 对于新访问者,记录访问者统计信息,然后更新访问者计数
- 将跟踪 cookie 添加到发送回访问者的响应中。您需要将此 cookie 设置为具有相当长的有效期,这样您就不会在 cookie 已过期的返回用户中收到很多“误报”。
下面是一些骨架代码(另存为StatsCounter.cs):
using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Transactions;
namespace hitcounter
{
public class StatsCounter : IHttpModule
{
// This is what we'll call our tracking cookie.
// Alternatively, you could read this from your Web.config file:
public const string TrackingCookieName = "__SITE__STATS";
#region IHttpModule Members
public void Dispose()
{ ;}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
context.PreSendRequestHeaders += new EventHandler(context_PreSendRequestHeaders);
}
void context_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
HttpResponse response = app.Response;
if (response.Cookies[TrackingCookieName] == null)
{
HttpCookie trackingCookie = new HttpCookie(TrackingCookieName);
trackingCookie.Expires = DateTime.Now.AddYears(1); // make this cookie last a while
trackingCookie.HttpOnly = true;
trackingCookie.Path = "/";
trackingCookie.Values["VisitorCount"] = GetVisitorCount().ToString();
trackingCookie.Values["LastVisit"] = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
response.Cookies.Add(trackingCookie);
}
}
private long GetVisitorCount()
{
// Lookup visitor count and cache it, for improved performance.
// Return Count (we're returning 0 here since this is just a stub):
return 0;
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
HttpRequest request = app.Request;
// Check for tracking cookie:
if (request.Cookies[TrackingCookieName] != null)
{
// Returning visitor...
}
else
{
// New visitor - record stats:
string userAgent = request.ServerVariables["HTTP_USER_AGENT"];
string ipAddress = request.ServerVariables["HTTP_REMOTE_IP"];
string time = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
// ...
// Log visitor stats to database
TransactionOptions opts = new TransactionOptions();
opts.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, opts))
{
// Update visitor count.
// Invalidate cached visitor count.
}
}
}
#endregion
}
}
通过将以下行添加到您的 Web.config 文件来注册此模块:
<?xml version="1.0"?>
<configuration>
...
<system.web>
...
<httpModules>
<add name="StatsCounter" type="<ApplicationAssembly>.StatsCounter" />
</httpModules>
</system.web>
</configuration>
(替换为您的 Web 应用程序项目的名称,或者如果您使用的是网站项目,则将其删除。
希望这足以让您开始尝试。正如其他人所指出的那样,对于一个实际的站点,最好使用谷歌(或其他一些)分析解决方案来解决这个问题。