Session_End中的会话和服务器变量

时间:2011-01-12 22:55:12

标签: asp.net iis-6

我有一个InProc会话网站,其中包含以下实现:

protected void Session_End(object sender, EventArgs e)
        {
            StreamWriter sw = null;
            string logFile = Server.MapPath("testSessionLog.txt");
            sw = new StreamWriter(logFile, true);
            sw.WriteLine("Session_End called at " + DateTime.Now);
            try
            {
                //Request is not available in this context 
                if (Request.ServerVariables["Logon_User"] != null && Request.ServerVariables["Logon_User"] != "")
                {
                    sw.WriteLine("Made it past Request.ServerVariables check");
                }
            }
            catch (Exception ex)
            {
                sw.Write("An error occured: " + ex.Message);
            }
            finally
            {
                sw.Close();
            }         
        }

我在堆栈上阅读了几篇文章(12),详细介绍了如何使用this.Session来获取HttpSessionState。那么Server.MapPath()和Request.ServerVariables()呢?我也无法在Session_End中使用它们。

我将这一段代码粘贴到一个button_Click事件中,它运行没有问题。这让我相信它是与Session_End相关的东西。

我每分钟将IIS6设置为recylcle一次。当我有一个开放的会话时,它会爆炸: 的错误:
    异常类型:HttpException
    异常消息:在此上下文中无法使用服务器操作

在事件查看器中它显示为事件1309.它抱怨包含Server.MapPath()的行

3 个答案:

答案 0 :(得分:4)

如前所述,在调用HttpContext时没有Session_End对象可以使用,因此访问ie。 ServerVariables根本没有任何意义。

对于MapPath,您可以调用不依赖于请求的静态方法HostingEnvironment.MapPath()

http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx

答案 1 :(得分:2)

问题是session_end不是从请求中触发的。它是由服务器上的超时触发的,在处理完sesion的最后一个请求很久之后。所以,没有请求对象。

如果您在会话中调用了Abandon(因为您已在请求的上下文中完成此操作),则可能不是这样。我没试过这个,但我怀疑它也不行。

我不了解MapPath - 也许它需要一个实时请求才能完成它。

答案 2 :(得分:-2)

毕竟可以访问Request和Server。您必须分别使用HttpContext.Current.Request和HttpContext.Current.Server。不是会话。 stack.

上两者的比较非常好