Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
835 views
in Technique[技术] by (71.8m points)

asp.net - Why HttpContext.Current.Session is null in Global.asax?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...