0

I wanna free some DB resources and set few flags when User Session Ends in ASP.NET Site. But when I write my code to access session variables in Session End method of Global.asax file, its getting called everytime the App starts, Why this weird behavior?

Secondly, I want to access user specific session variables and free them up in DB on Session End. Thus I am using few session Variables where I am setting them in a webmethod on a Page and trying to access them on Session End. But since Session end is being called on App start up its always throws Null reference exception.

Here is mycode. for Setting up a variable in Webmethod in a .aspx page

   [WebMethod(EnableSession=true)]
protected void checkUser()
        {
            Session["TestObject"] = "Hello I am session";
}

In my global.asax file I am trying to access as follows in Session_End method

void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
        if (this.Context.Session != null && this.Context != null)
        {
            string k = this.Session["TestObject"].ToString();
        }

    }

I even tried HttpContext.current.Session etc.. but none worked. All are throwing exception as Session end is called on App start up and even when session timed out.

Programmerzzz
  • 1,237
  • 21
  • 48
  • When Session_End is called, there is no HttpContext (it's called 20 mins *after* the user was seen last) – Hans Kesting Jul 17 '15 at 08:04
  • test *first* for `this.Context != null`, so accessing `this.Context.Session` is prevented when Context is null. – Hans Kesting Jul 17 '15 at 08:04
  • see also http://stackoverflow.com/q/2030113/121309 – Hans Kesting Jul 17 '15 at 09:27
  • Yup...if I use this. Context...even though it's not null it doesn't contain my session variable I need. Setting session["TestObject"] in .aspx.cs and trying to access it as this.session ["TestObject"] in session_end refer to different objects? – Programmerzzz Jul 17 '15 at 13:26
  • Also why session_end is being called on app start up at the first place? Any misunderstanding from my side...pls clarify – Programmerzzz Jul 17 '15 at 13:28

0 Answers0