Global Session_End 没被执行(触发)根本原因探究
若网站要实现在线用户功能,当用户登录时要在 Session_Start 方法中把用户添加到在线列表中,而用户退出时又需要在 Session_End 方法中把用户从在线列表中删除。有的时候,在 Session_End 方法中把用户删除却怎么也删不掉,似乎Session_End没被执行,我们常常以为是删除代码有问题,可不在 Session_End 方法执行删除用户代码又能正常删除用户,说明删除代码无问题,而是 Session_End 方法有问题,问题根本原因在哪呢?
我们首先来看 C# 语言对 Session_End 方法是如何规定的:
1、Session_End 方法中的代码如果有错,会立即返回,并且不会记录错误也不会抛出任何异常,也不能用 Respone.Write 方法输出错误;
2、Session_End 方法中不能使用 Server.MapPath>、Request、Cache、HttpContext.Current 等方法或类;
3、需要把 Web.Config 配置文件中 sessionState mode="InProc" 模式设置为 InProc。
所以,如果遇到 Session_End 没被执行(触发),不妨先检查是否违反了以上规定。通常容易犯的错误是在 Session_End 方法中或其调用的方法中使用了 Server.MapPath、Request、Cache、HttpContext.Curren;如果使用了它们,换一种方法实现,代码就能正常执行了。
Global Session_End 没被执行(触发)举例
1、在 Session_End 方法中使用了 Server.MapPath
protected void Session_End(object sender, EventArgs e)
{
string path = "/temp/map.txt";
path = Server.MapPath(path);//不允许在 Session_End 方法中使用 Server.MapPath
}
2、Session_End 方法中调用的方法使用了 HttpContext.Curren
protected void Session_End(object sender, EventArgs e)
{
string path = "/temp/map.txt";
path = Server.MapPath(path);//不允许在 Session_End 方法中使用 Server.MapPath
}
public void delOnline()
{
if(HttpContext.Current.Cache["user"] != null)
{
//不允许在 Session_End 方法调用的方法中使用 HttpContext.Current 和 Cache
string user = (HttpContext.Current.Cache["user"]).ToString();
}
}