为什么HttpContext.Current.Session在Global.asax中为null?

Pét*_*ter 15 asp.net session-variables global-asax

我正在使用VS2010并创建了一个简单的asp.Web表单应用程序,使用Development Server对其进行测试.
我尝试在会话中存储用户数据 - 从sql server查询 - 因为我不想在每个请求中访问数据库.我正在使用'Application_AuthenticateRequest'和'Session_Start'方法.
第一轮:调用AuthenticateRequest.运行以下代码:

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;
      }
    }
Run Code Online (Sandbox Code Playgroud)

_current变量是通过静态属性发布的私有静态字段.在第一轮中,Session是null,我认为没关系,因为Session_Start尚未调用.Session_Start看起来像这样:

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

在下一轮中,当然没有调用Session_Start,但在AuthenticateRequest中我无法访问会话.HttpContext.Current.Session为null,this.Session引用抛出HttpException,表示"会话状态在此上下文中不可用".

但是我可以从任何page_load事件访问Session,但这是一个不好的做法,我认为我将每个page_load放入身份验证.知道怎样才能访问Session?

谢谢你的建议,
Péter

Tor*_*son 35

你无法在Application_AuthenticateRequest上使用Session,因为它当时没有受到限制.

我认为您可以使用事件Application_AcquireRequestState.

  • 我认为有必要应用这个测试:if(System.Web.HttpContext.Current.Session!= null)因为Application_AcquireRequestState可以被调用一次以上,并且会话在某些情况下可以为null.这是我的工作方式,我从这里开始:http://stackoverflow.com/questions/9897112/global-asax-event-that-has-access-to-session-state (4认同)
  • @TorbjörnHansson:有时候它是空的,你知道为什么吗? (2认同)