Why HttpContext.Current.Session is null in Global.asax?

两盒软妹~` 提交于 2019-11-27 03:15:10

问题


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


回答1:


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.




回答2:


try to use the below code in page_Load

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


来源:https://stackoverflow.com/questions/4185871/why-httpcontext-current-session-is-null-in-global-asax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!