这两天一直心情不好今天尤其的坏,刚刚重新启动了我的那个秘密项目,找了点资料学习了Global.asax的使用方法,在项目里面加上了计数器的功能.
参考了很多资料,发现资料里面的东西确实很多不太适合自己,所以把自己的心得贴出来供大家参考
我给网站添加了Global.asax,App_Code文件夹下Global.asax.cs,文本文件Site_Counter.txt并写入数字0,代码分别如下:
Global.asax
<%
@ Application Inherits
=
"
Linker.Global
"
Language
=
"
C#
"
%>
Global.asax.cs
using
System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
namespace Linker
... {
/**//// <summary>
/// Global 的摘要说明
/// </summary>
public class Global : HttpApplication
...{
public Global()
...{
//
// TODO: 在此处添加构造函数逻辑
//
}
protected void Application_Start(object sender, EventArgs e)
...{
// 在应用程序启动时运行的代码
StreamReader rd = new StreamReader(Server.MapPath("Site_Counter.txt"));
Application.Lock();
Application["Site_Counter"] = int.Parse(rd.ReadLine());
Application.UnLock();
rd.Close();
}
protected void Session_Start(object sender, EventArgs e)
...{
// 在新会话启动时运行的代码
Application.Lock();
Application["Site_Counter"] = Convert.ToInt32(Application["Site_Counter"]) + 1;
Application.UnLock();
StreamWriter wt = new StreamWriter(Server.MapPath("Site_Counter.txt"), false);
Application.Lock();
wt.WriteLine(Application["Site_Counter"]);
Application.UnLock();
wt.Close();
}
}
}
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
namespace Linker
... {
/**//// <summary>
/// Global 的摘要说明
/// </summary>
public class Global : HttpApplication
...{
public Global()
...{
//
// TODO: 在此处添加构造函数逻辑
//
}
protected void Application_Start(object sender, EventArgs e)
...{
// 在应用程序启动时运行的代码
StreamReader rd = new StreamReader(Server.MapPath("Site_Counter.txt"));
Application.Lock();
Application["Site_Counter"] = int.Parse(rd.ReadLine());
Application.UnLock();
rd.Close();
}
protected void Session_Start(object sender, EventArgs e)
...{
// 在新会话启动时运行的代码
Application.Lock();
Application["Site_Counter"] = Convert.ToInt32(Application["Site_Counter"]) + 1;
Application.UnLock();
StreamWriter wt = new StreamWriter(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
"
]);
呵呵,大功告成,测试下吧,是不是已经看到了呢?