实施访客计数器

Lal*_*rik 5 asp.net count popularity visitor

我是一个新手,并使用ASP .Net 2.0和C#2005开发一个网站.我想添加一个设施来计算no.访问我的网站.我已经收集了使用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地址,浏览器使用,访问日期和时间,屏幕分辨率等.我该怎么做?

等待建议.

Lalit Kumar Barik

elo*_*0ka 6

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

  1. 检查Request.Cookies是否包含跟踪Cookie
  2. 如果跟踪cookie不存在,这可能是一个新访问者(否则,他们的cookie已过期 - 请参阅4.)
  3. 对于新访问者,请记录访问者统计信息,然后更新访问者计数
  4. 将跟踪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
    }
}
Run Code Online (Sandbox Code Playgroud)

通过将以下行添加到Web.config文件来注册此模块:

<?xml version="1.0"?>
<configuration>
    ...
    <system.web>
        ...
        <httpModules>
          <add name="StatsCounter" type="<ApplicationAssembly>.StatsCounter" />
        </httpModules>
    </system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)

(替换为Web应用程序项目的名称,或者如果您使用的是网站项目,则将其删除.

希望这足以让你开始尝试.正如其他人已经指出的那样,对于一个实际的网站,你最好还是使用谷歌(或其他)分析解决方案.


omo*_*oto 1

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