如何统计网站访问量,代码实现使用全局变量 Application,start,end,Session_start,Session_end事件

步骤1:新建一个Global.asax  全局应用程序类

<%@ Application Language="C#"%>
<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码
        long totalCount = 0; //总访问数
        int todayCount = 0;//今天在线人数
        //先从XML中取得访问数
        string xmlFilePath = Server.MapPath("~/") + "xml\\count.xml"; //XML文件路径
        System.Data.DataSet ds = new System.Data.DataSet();
        ds.ReadXml(xmlFilePath);
        totalCount = Int64.Parse(ds.Tables[0].Rows[0]["TotalCount"].ToString().Trim());
        //设置Application,设置在线数量,总访问数量
        Application["total_count"] = totalCount;
        Application["today_count"] = todayCount;
    }
    void Session_Start(object sender, EventArgs e)
    {
        // 在新会话启动时运行的代码
        Application.Lock();//锁定
        long totalCount = 0; //总访问数
        int todayCount = 0;//今天访问数
        totalCount = Convert.ToInt64(Application["total_count"]);
        todayCount = Convert.ToInt32(Application["today_count"]);
        totalCount++;//用户登录,以后才修改访问总数
        todayCount++;//在线用户数量加 1
        Application["total_count"] = totalCount;
        Application["today_count"] = todayCount;
        //把访问数写如到XML文件中
        string xmlFilePath = Server.MapPath("~/") + "xml/count.xml"; //XML文件路径
        System.Xml.XmlDocument xmlObj = new System.Xml.XmlDocument();
        xmlObj.Load(xmlFilePath);
        System.Xml.XmlNode xmlRootOjb = xmlObj.SelectSingleNode("Web/AccessInfo/TotalCount");
        xmlRootOjb.InnerText = totalCount.ToString();//增加总的访问量,并修改xml总访问量的值
        xmlObj.Save(xmlFilePath);
        Application.UnLock();//解锁
    }
    void Session_End(object sender, EventArgs e)
    {   //这里主要计算登录用户
        Application.Lock();
        Application["today_count"] = Int32.Parse(Application["today_count"].ToString()) - 1;
        //当用户离开站点的时候,在线总数减1
        Application.UnLock();
    }       
</script>

步骤2:新建一个xml文档用来存放 在线人数

<?xml version="1.0" encoding="utf-8"?>
<Web>
  <AccessInfo>
    <TotalCount>4</TotalCount>
  </AccessInfo>
</Web>

步骤3:在aspx中输出 统计的在线人数

Response.Write(Application["today_count"]);

ok大功告成!

经过本人的测试,感觉还是有点问题的,怪怪的。留作以后备用吧。

posted @ 2011-05-18 21:59  小2010  阅读(591)  评论(0编辑  收藏  举报