ASP.NET访问者计数器

时间:2011-09-27 11:39:57

标签: c# asp.net counter

我正在为我的网页创建一个计数器。无法实现的是,每次用户访问我的asp.net应用程序时,它都会将数据存储到数据库中。我正在使用Global.asax和事件Application_Start。这是我的代码。

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        WebpageCounter.SaveVisitor(new WebpageVisitor()
        {
            VisitorIP = HttpContext.Current.Request.UserHostAddress,
            VisitedOn = DateTime.Now
        });
    }

但它永远不会将任何东西存储到数据库中。 SaveVisitor函数已经过测试,并且功能正常。

有什么建议吗?

4 个答案:

答案 0 :(得分:4)

Application_Start()仅在应用程序域的生命周期内调用一次 - 而不是针对您网站的每个请求。另请参阅"ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0"

答案 1 :(得分:3)

背后代码的代码:

C#

    protected void Page_Load(object sender, EventArgs e)
    {
        this.countMe();

        DataSet tmpDs = new DataSet();
        tmpDs.ReadXml(Server.MapPath("~/counter.xml"));

        lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
    }

    private void countMe()
    {
        DataSet tmpDs = new DataSet();
        tmpDs.ReadXml(Server.MapPath("~/counter.xml"));

        int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());

        hits += 1;

        tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();

        tmpDs.WriteXml(Server.MapPath("~/counter.xml"));

    }

VB.NET

    Protected Sub Page_Load(sender As Object, e As EventArgs)
        Me.countMe()

        Dim tmpDs As New DataSet()
        tmpDs.ReadXml(Server.MapPath("~/counter.xml"))

        lblCounter.Text = tmpDs.Tables(0).Rows(0)("hits").ToString()
    End Sub

    Private Sub countMe()
        Dim tmpDs As New DataSet()
        tmpDs.ReadXml(Server.MapPath("~/counter.xml"))

        Dim hits As Integer = Int32.Parse(tmpDs.Tables(0).Rows(0)("hits").ToString())

        hits += 1

        tmpDs.Tables(0).Rows(0)("hits") = hits.ToString()

        tmpDs.WriteXml(Server.MapPath("~/counter.xml"))
    End Sub

XML文件将如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<counter>
  <count>
     <hits>0</hits>
  </count>

答案 2 :(得分:2)

Application_Start仅在创建流程时运行 - 而不是每次访问。

您可以改用Application_BeginRequest。

答案 3 :(得分:1)

IIS可以记录此信息,然后使用优秀的logparser进行查询/转换。您也可以将Google Analytics放在您的网站上 - 除了最繁忙的网站之外,其免费版本已足够。如果你仍然觉得自己需要这样做,那么Application_BeginRequest是一个更好的记录它的地方。

编辑:您可以将其实现为模块,例如the MSDN Custom Module Walkthrough,然后您的应用可能会更加模块化