加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

使用ASP.Net和C#计算WebSite中的访问者数量

发布时间:2020-12-16 04:21:10 所属栏目:asp.Net 来源:网络整理
导读:我想跟踪我网站的访问者数量. 我在Global.asax类中尝试了以下代码, script runat="server" public static int count = 0; void Application_Start(object sender,EventArgs e) { Application["myCount"] = count; } void Session_Start(object sender,EventA
我想跟踪我网站的访问者数量.

我在Global.asax类中尝试了以下代码,

<script runat="server">

  public static int count = 0;
  void Application_Start(object sender,EventArgs e) 
  {
    Application["myCount"] = count;
  }

  void Session_Start(object sender,EventArgs e) 
  {
    count = Convert.ToInt32(Application["myCount"]);
    Application["myCount"] = count + 1;
  }

</script>

我正在检索aspx页面中的值,如下所示:

protected void Page_Load(object sender,EventArgs e)
{
  int a;
  a = Convert.ToInt32((Application["myCount"]));
  Label4.Text = Convert.ToString(a);
  if (a < 10)
    Label4.Text = "000" + Label4.Text ;
  else if(a<100)
    Label4.Text = "00" + Label4.Text;
  else if(a<1000)
    Label4.Text = "0" + Label4.Text;
}

上面的编码工作正常.它正确生成访问者,但问题是当我重新启动系统时,count变量再次从0开始,这在逻辑上是错误的.

我希望count的值从最后一个计数值增加1.

那么有人能告诉我如何完成这项任务吗?

请帮帮我!
提前致谢!

解决方法

如果您希望计数在应用程序重新启动时继续递增,则需要将值存储在某个位置 – 在数据库或某个文件中,并在应用程序启动时加载该值.

此外,您可以使用以下内容确保显示的计数始终至少为4个字符:

int a;
a = Convert.ToInt32(Application["myCount"]);
Label4.Text = a.ToString("0000");

有关详细信息,请参阅Custom Numeric Format Strings.

编辑以回复评论

就个人而言,我建议使用数据库而不是写入文件系统,至少有以下原因:

>根据您的主机,设置数据库可能比启用对文件系统的写访问要容易得多.
>使用数据库将允许您将其存储为int而不是字符串.
>在交通拥挤的情况下,您会遇到多个线程尝试打开文本文件进行写访问的问题 – 这将导致文件锁定,并导致您不需要的瓶颈.

各种资源将告诉您如何从代码连接到数据库,一个好的起点是How To: Connect to SQL Server,并查看“What are the alternatives”下的方法,了解如何查询和更新数据库的详细信息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读