17

I'm using VS2010 and created a simple asp. web forms application, using Development Server to test it.
I try to store user data - queried from sql server - in the session, since I don't want to access database in every request. I'm using the 'Application_AuthenticateRequest' and the 'Session_Start' methods.
First round: AuthenticateRequest called. The following code ran:

public static void Initialize(string login_name, bool force_refresh)
    {
      HttpSessionState Session = HttpContext.Current.Session;
      object o = Session == null ? null : Session["EMPLOYEE_DATA"];
      if (force_refresh || o == null || o.GetType() != typeof(Employee) || (o as Employee).login_name!= login_name)
      {
        _current = UIManager.GetEmployee(login_name);
        if (Session != null)
        {
          Session["EMPLOYEE_DATA"] = _current;
        }
      }
      else
      {
        _current = (Employee)o;
      }
    }

The _current variable is a private static field published through a static property. In the first round the Session is null, and I think it's ok because the Session_Start not called yet. The Session_Start looks like this:

protected void Session_Start(object sender, EventArgs e)
{
  Session["EMPLOYEE_DATA"] = EmployeeFactory.Current;
}

In the next round the Session_Start is not called of course but in the AuthenticateRequest I can't access to the session. The HttpContext.Current.Session is null and the this.Session reference throw a HttpException says the "Session state is not available in this context".

However I can access the Session from any of the page_load events but it's a bad practice I think that I put authentication every page_load. Any idea how can I access to the Session?

Thanks for advice,
Péter

2 Answers 2

38

You're not able to use Session on the Application_AuthenticateRequest becauase it's not bound at that moment.

I think you're able to use the event Application_AcquireRequestState.

4
  • Thank You. It was the solution.
    – Péter
    Nov 15, 2010 at 16:05
  • 2
    @Torbjörn Hansson: Sometimes it's null, do you have any idea why that?
    – Homam
    Jul 17, 2011 at 19:35
  • Wish I could upvote this a thousand times! That simple change just ended hours of suffering. Mar 20, 2013 at 17:20
  • 4
    I think it's necessary to apply this test: if (System.Web.HttpContext.Current.Session != null) because the Application_AcquireRequestState can be called more then once and the session can be null in some case. This is how it works for me, I have from here: stackoverflow.com/questions/9897112/… Dec 13, 2013 at 22:34
-2

try to use the below code in page_Load

Response.AppendHeader("Refresh", Convert.ToString(Session.Timeout * 15) + "; 
URL=SessionExpPage.aspx");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.