如何在asp.net 4.0中使用global.asax文件计算天数

时间:2013-02-20 12:57:22

标签: asp.net datetime global-asax days

Clickhere Global.asax.cs

      namespace WebApplication7
     {
    public class Global : System.Web.HttpApplication
      {
    private static int countdays=0;

    protected void Application_Start(object sender, EventArgs e)
    {
        countdays = 0;
    }

    protected void Session_Start(object sender, EventArgs e)
    {
        countdays += 1;
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {

    }

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {

    }

    protected void Application_Error(object sender, EventArgs e)
    {

    }

    protected void Session_End(object sender, EventArgs e)
    {
        countdays -= 1;
    }

    protected void Application_End(object sender, EventArgs e)
    {

    }
    public static int CountNo { get { return countdays; } }
  }
}

Global.apsx

  <body>
  <form id="fromHitCounter" method="post" runat="server">
  Total number of days since the Web server started:
 <asp:label id="lblCount" runat="server"></asp:label><br />
 </form>
 </body>

Global.aspx.cs

      private void Page_Load(object sender, System.EventArgs e)

        {

      int Countdays = HitCounters.Global.Countdays;//Hit counter does not exist  


      lblCount.Text = Countdays.ToString();

        }

如何使用global.asax文件计算asp.net中的天数计数器,在Global.aspx.cs中,当前上下文中不存在错误点击计数器

1 个答案:

答案 0 :(得分:2)

我不会问为什么,我可能不会喜欢你给我的理由。不过你在这里不算几天。你正在计算会话开始。

你真正想要做的是这样的事情:

public class Global : System.Web.HttpApplication
{

    private static DateTime started;
    private static int days;

    protected void Application_Start(object sender, EventArgs e)
    {
        started = DateTime.UtcNow;
        days = 0;
    }

    protected void Session_Start(object sender, EventArgs e)
    {
        TimeSpan ts = DateTime.UtcNow - started;
        days = (int)ts.TotalDays;
    }

    ...

  }
}

然而,这是假设会话事件触发并且您也忽略了应用程序可以并且确实被卸载的事实,您的应用程序可能不会在一天内保持加载。

您的链接指向计算网站访问次数,这与计算天数或获取Web服务器运行时间不同。这也是一次非常糟糕的尝试,因为它没有考虑来自同一用户等的重复访问,并且在应用程序域卸载时并不真正持久。