Global.asax文件(自己添加,先添加.txt文件,在修改后缀),包含了用于响应ASP.NET或HttpModule引发的应用程序(或整个网站)事件的代码。
Global.asax文件为Application(可以当做整个应用程序的全局对象)和Session(整个应用程序和单个建立连接用户的公共对象)对象定义了5个基本事件。
1. 事件Application_Start(Object sender,EventArges e)在Application对象开始时被触发,在该事件中,应用程序可以进行一些与整个应用程序相关的初始化工作。
2. 事件Application_End(Object sender,EventArges e)在Application对象结束时被触发。
3. 事件Application_Error(Object sender,EventArges e)在Application对象发出错误时被触发。
4. 事件Session_Start(Object sender,EventArges e)在Session对象开始时被触发,在该事件中,应用程序可以进行一些与单个用户相关的初始化工作。
5. 事件Session_End(Object sender,EventArges e)在Session对象结束时被触发,在该事件中,应用程序可以进行一些与单个用户相关的信息更新工作。
下面是一个使用上面技术实现“统计在线人数”的例子。
先在网站中添加一个Global.asax文件
<%@ Application
Language="C#"
%>
<script runat="server">
void
Application_Start(object sender, EventArgs e)
{
//
在应用程序启动时运行的代码
Application["counter"] = 0;
}
void
Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
}
void
Application_Error(object sender, EventArgs e)
{
//
在出现未处理的错误时运行的代码
}
void
Session_Start(object sender, EventArgs e)
{
//
在新会话启动时运行的代码
Application.Lock();//先上锁
Application["counter"] = (int)Application["counter"] + 1;
Application.UnLock();
}
void
Session_End(object sender, EventArgs e)
{
//
在会话结束时运行的代码。
//
注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
//
InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
//
或 SQLServer,则不会引发该事件。
Application.Lock();
Application["counter"] = (int)Application["counter"] - 1;
Application.UnLock();
}
</script>
使用这些数据
protected void Page_Load(object sender, EventArgs
e)
{
string
conter = Application["counter"].ToString();
Response.Write("当前在线的人数有<font
color=red size=5>" + conter + "</font>人");//若无法结束Session_End的话,
//那么输出的是总共访问人数
}
浙公网安备 33010602011771号