asp.net 设计站点计数器

问题:

使用 Session 对象设计一个站点计数器,要求将来访人数存放在站点内的 counter.txt 文件内,该数字不会因服务器或网站重新启动而丢失,刷新页面也不会引起数字变化,程序运行时要求将当前会话的 ID 值显示到页面中。

代码:

需要先创建 counter.txt 文本文档,并赋初值为0;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
          
   
    protected void Page_Load(object sender, EventArgs e)
    {
          
   
        string FilePath = "C:/Users/13137/Documents/.net/job5-2/counter.txt"; //counter.txt文件路径
        StreamReader sr = new StreamReader(FilePath);
        int count = int.Parse(sr.ReadLine());
        sr.Close();
        if (Session["counter"] == null)
        {
          
   
            Session["counter"] = "";
            count = count + 1;
            StreamWriter sw = new StreamWriter(FilePath);
            sw.WriteLine(count);
            sw.Close();
            Response.Write("当前sessionID为:" + Session.SessionID + "<br>你是第" + count.ToString() + "位访问者");
        }
    }
}

运行演示:

经验分享 程序员 微信小程序 职场和发展