计数器

本文介绍了一个简单的 ASP.NET 应用程序中实现的访问计数器功能,该计数器通过读取和更新文件中的计数来跟踪网站访问次数,并使用 Application 对象进行会话管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

protected void Application_Start(Object sender, EventArgs e)
        
{
            
uint count=0;
            StreamReader srd;
            
string file_path=Server.MapPath ("Counter/counter.txt");
            srd
=File.OpenText (file_path);
            
while(srd.Peek ()!=-1)
            
{
                
string str=srd.ReadLine ();
                count
=UInt32.Parse (str);
            }

            
object obj=count;
            Application[
"counter"]=obj;
            srd.Close ();

        }
 
    protected void Session_Start(Object sender, EventArgs e)
        
{
            Application.Lock ();
            
//数值累加,注意这里使用了装箱(boxing)
            uint jishu=0;
            jishu
=(uint)Application["counter"];
            jishu
=jishu+1;
            
object obj=jishu;
            Application[
"counter"]=obj;            

        
            
//将数据记录写入文件
            string file_path=Server.MapPath ("Counter/counter.txt");
            StreamWriter fs
=new StreamWriter(file_path,false); 
            fs.WriteLine (jishu);
            fs.Close ();
        
            Application.UnLock ();

            ZzbDbproClass m_Dbpro
=new ZzbDbproClass();
            
string m_IPAddress=m_Dbpro.G_User_IP();
            m_Dbpro.Add_OT_SiteLog( System.DateTime.Now, m_IPAddress, System.DateTime.Now.Month, System.DateTime.Now.Year);
            m_Dbpro.Upt_OT_SiteCount(
int.Parse(Application["counter"].ToString()),"");
        }
protected void Application_End(Object sender, EventArgs e)
        
{
            
//装箱
            uint js=0;
            js
=(uint)Application["counter"];
            
//object obj=js;
            
//Application["counter"]=js;
            
//将数据记录写入文件
            string file_path=Server.MapPath ("Counter/counter.txt");
            StreamWriter fs
=new StreamWriter(file_path,false); 
            fs.WriteLine(js);
            fs.Close ();
        }
//禁cache
Response.Buffer=true;
            Response.ExpiresAbsolute
=DateTime.Now.AddSeconds(-1);
            Response.Expires
=0;
            Response.CacheControl
="no-cache";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值