怎么样通过Asp.net 2.0使用Global.asax制作网站计数器?
这两天一直心情不好今天尤其的坏,刚刚重新启动了我的那个秘密项目,找了点资料学习了Global.asax的使用方法,在项目里面加上了计数器的功能.
参考了很多资料,发现资料里面的东西确实很多不太适合自己,所以把自己的心得贴出来供大家参考
我给网站添加了Global.asax,App_Code文件夹下Global.asax.cs,文本文件Site_Counter.txt并写入数字0,代码分别如下:
Global.asax
<%@ApplicationInherits="Linker.Global"Language="C#"%>
Global.asax.cs
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.IO;
namespaceLinker
{
///<summary>
///Global的摘要说明
///</summary>
publicclassGlobal:HttpApplication
{
publicGlobal()
{
//
//TODO:在此处添加构造函数逻辑
//
}
protectedvoidApplication_Start(objectsender,EventArgse)
{
//在应用程序启动时运行的代码
StreamReaderrd=newStreamReader(Server.MapPath("Site_Counter.txt"));
Application.Lock();
Application["Site_Counter"]=int.Parse(rd.ReadLine());
Application.UnLock();
rd.Close();
}
protectedvoidSession_Start(objectsender,EventArgse)
{
//在新会话启动时运行的代码
Application.Lock();
Application["Site_Counter"]=Convert.ToInt32(Application["Site_Counter"])+1;
Application.UnLock();
StreamWriterwt=newStreamWriter(Server.MapPath("Site_Counter.txt"),false);
Application.Lock();
wt.WriteLine(Application["Site_Counter"]);
Application.UnLock();
wt.Close();
}
}
}
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.IO;
namespaceLinker
{
///<summary>
///Global的摘要说明
///</summary>
publicclassGlobal:HttpApplication
{
publicGlobal()
{
//
//TODO:在此处添加构造函数逻辑
//
}
protectedvoidApplication_Start(objectsender,EventArgse)
{
//在应用程序启动时运行的代码
StreamReaderrd=newStreamReader(Server.MapPath("Site_Counter.txt"));
Application.Lock();
Application["Site_Counter"]=int.Parse(rd.ReadLine());
Application.UnLock();
rd.Close();
}
protectedvoidSession_Start(objectsender,EventArgse)
{
//在新会话启动时运行的代码
Application.Lock();
Application["Site_Counter"]=Convert.ToInt32(Application["Site_Counter"])+1;
Application.UnLock();
StreamWriterwt=newStreamWriter(Server.MapPath("Site_Counter.txt"),false);
Application.Lock();
wt.WriteLine(Application["Site_Counter"]);
Application.UnLock();
wt.Close();
}
}
}
然后在需要显示的页面显示系统 就可以了
比如简单的:
Label_Site_Counter.Text=Convert.ToString(Application["Site_Counter"]);
呵呵,大功告成,测试下吧,是不是已经看到了呢?
本文地址:http://www.45fan.com/a/question/73714.html