我想跟踪我网站的访问者数量。
我在 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;
}
上面的编码工作正常。它正确生成访客,但问题是当我重新启动系统时,计数变量再次从 0 开始,这在逻辑上是错误的。
我希望 count 的值从最后一个计数值增加 1。
那么谁能告诉我如何完成这项任务?
请帮帮我!
提前致谢!
最佳答案
如果您希望计数在应用程序重新启动时不断增加,您需要将值存储在某处 - 数据库或文件中的某处,并在应用程序启动时加载该值。
此外,您可以使用以下内容来确保显示的计数始终至少为 4 个字符:
int a;
a = Convert.ToInt32(Application["myCount"]);
Label4.Text = a.ToString("0000");
见 Custom Numeric Format Strings了解更多信息。
编辑回复评论
就个人而言,我建议使用数据库而不是写入文件系统,至少有以下原因:
int
而不是 string
. 各种资源会告诉您如何从您的代码连接到数据库,一个不错的起点是 How To: Connect to SQL Server ,并查看“What are the alternatives”下的方法以了解有关如何查询和更新数据库的详细信息。
关于asp.net - 使用 ASP.Net 和 C# 计算网站中的访问者数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1508529/