开发者

Sessions and server variables in Session_End

开发者 https://www.devze.com 2023-02-03 18:26 出处:网络
I have an InProc session website with the following implementation: protected void Session_End(object sender, EventArgs e)

I have an InProc session website with the following implementation:

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();
            }         
        }

I read a couple articles (1,2) on stack that go into details about using this.Session to get to get to HttpSessionState. What about Server.MapPath() and Request.ServerVariables()? I can't get these to work within Session_End either.

I pasted this same blob of code into a button_Click event and it runs without issues. This leads me to believe that it is something related to Session_End.

I setup IIS6 to recylcle once per minute. When I have an open session it blows up with: Error:

Exception type: HttpException

Exception message: Server operation is not available in this context

In the event viewer it shows up as event 1309. It complains about the line containing Server.MapPath()


As already mentioned there is no HttpContext object to work with when Session_End is being called, so accessing ie. ServerVariables doesn't make any sense at all.

For MapPath you can call the static method HostingEnvironment.MapPath() which doesn't rely on being in a request.

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


The problem is that session_end is not fired from a request. it is triggered by a time out on the server, long after the last request on the sesion has been processed. So, there is no request object to be had.

This may not be true if you have called Abandon on the session (since you have done that within the context of a request). I haven't tried this, but I suspect it would not work either.

I don't know about MapPath - maybe it requires a live Request to do its thing.


It is possible to get to Request and Server after all. You have to use HttpContext.Current.Request and HttpContext.Current.Server respectively. Not session. There's a pretty good comparison of the two on stack.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号