【问题标题】:Implementing a visitor counter实施访客计数器
【发布时间】:2009-03-21 09:45:37
【问题描述】:

我是一个新手,正在使用带有 C# 2005 的 ASP .Net 2.0 开发一个网站。我想添加一个工具来计算编号。我网站的访问者。我已经收集了使用 Global.asax 添加此功能的基本信息。我通过在 system.web 部分下添加“”行对 Web.config 进行了修改。

我正在使用表格来记录访客人数。但我不知道如何完成任务。我的默认 Global.asax 文件带有不同的部分 Application_Start、Application_End、Application_Error、Session_Start 和 Session_End。我试图在 Application_Start 部分中提取计数器的当前值并将其存储在全局变量中。我将增加 Session_Start 中的计数器并将修改后的值写入 Application_End 中的表。

我尝试使用公共子程序/函数。但是我应该把这些子程序放在哪里呢?我试图在 Global.asax 本身中添加子例程。但是现在我遇到了错误,因为我无法在 Global.asax 中添加对 Data.SqlClient 的引用,并且我需要对 SqlConnection、SqlCommand、SqlDataReader 等的引用来实现这些功能。我必须为每个子例程添加类文件吗?请指导我。

我还想对我的网站实施跟踪功能,并存储我的网站访问者的 IP 地址、使用的浏览器、访问日期和时间、屏幕分辨率等。我该怎么做?

等待建议。

拉利特·库马尔·巴里克

【问题讨论】:

  • 我已经检查过了,能够引用 System.Data.SQLClient 命名空间并使用这些类连接到 global.asax 文件中的数据库。您遇到了什么错误?
  • 我将引用添加为使用 System.Data.SqlClient;在 Global.asax 中并出现错误。现在我已更改为 Global.asax 中的 并且没有出现任何错误。如何实现可在所有页面/表单中访问的全局变量?拉利特库马尔巴里克

标签: asp.net count popularity visitor-pattern


【解决方案1】:

对于简单的实现,您可以使用自定义 HttpModule。对于您的应用程序的每个请求,您将:

  1. 检查 Request.Cookies 是否包含跟踪 Cookie
  2. 如果跟踪 cookie 不存在,这可能是新访问者(否则,他们的 cookie 已过期 -- 参见 4。)
  3. 对于新访问者,记录访问者统计信息,然后更新访问者计数
  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 应用程序项目的名称,如果您使用的是网站项目,则将其删除。

希望这足以让您开始尝试。不过,正如其他人所指出的那样,对于实际站点,最好使用 Google(或其他)分析解决方案。

【讨论】:

    【解决方案2】:

    使用Google Analytics。不要试图重新发明轮子,除非 a) 轮子没有做你想做的事情,或者 b) 你只是想弄清楚轮子是如何工作的

    【讨论】:

    • 感谢您的友好回复。我将按照建议使用 Google Analytics。但我仍然有兴趣添加我自己的访客柜台风格/版本,至少可以学习和扩展我的知识。我想知道如何在 ASP.Net 2.0 中实现公共/公共函数和全局变量。 L.K.巴里克
    • Gareth> 如果使用谷歌分析,那么如何在您的网页上显示访客数?或者我可以使用的任何其他网络访问者计数器不会在其中放置自己的 URL 或广告?
    【解决方案3】:

    Google 分析脚本正是您所需要的。因为会话,也会为爬虫打开。

    【讨论】:

    • 另一种方法是使用 IIS 日志文件,有很多工具可以提供对它们的解析。
    【解决方案4】:

    我只能同意 Gareth 的建议,即使用现有的流量分析。如果您不喜欢向 Google 提供有关您网站流量的数据,您还可以下载日志文件并使用众多可用的web server log file analysis tools 之一对其进行分析。

    【讨论】:

    • Adrian> 如果使用谷歌分析,那么如何在您的网页上显示访客数?或者我可以使用的任何其他网络访问者计数器不会在其中放置自己的 URL 或广告?
    猜你喜欢
    • 2020-12-17
    • 1970-01-01
    • 2020-03-11
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多