2011-05-12 91 views
36

我正在使用ASP.NET MVC,我需要在Application_BeginRequest上设置会话变量。问题在于此时对象HttpContext.Current.Session始终是null在Application_BeginRequest中设置会话变量

protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
    if (HttpContext.Current.Session != null) 
    { 
     //this code is never executed, current session is always null 
     HttpContext.Current.Session.Add("__MySessionVariable", new object()); 
    } 
} 
+0

产品/排序重复的:http://stackoverflow.com/questions/765054/whens-the-earliest-i-can -access-some-session-data-in-global-asax/ – 2013-03-01 05:54:52

回答

64

在Global.asax中尝试AcquireRequestState。会议在此事件,触发为每个请求可用:

void Application_AcquireRequestState(object sender, EventArgs e) 
{ 
    // Session is Available here 
    HttpContext context = HttpContext.Current; 
    context.Session["foo"] = "foo"; 
} 

Valamas - 建议编辑:

与MVC 3中成功地使用这一点,并避免了会话错误。

protected void Application_AcquireRequestState(object sender, EventArgs e) 
{ 
    HttpContext context = HttpContext.Current; 
    if (context != null && context.Session != null) 
    { 
     context.Session["foo"] = "foo"; 
    } 
} 
+7

我正在使用MVC 3,但这不起作用。会话为空。 – 2011-05-24 20:16:11

+2

这正是我所需要的。 – 2012-04-27 04:23:52

+4

这不适用于我context.session为空 – JBeckton 2012-09-06 15:25:53

11

也许你可以改变的范例......也许你可以使用HttpContext类的其他财产,更具体HttpContext.Current.Items如图所示波纹管:

protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
    HttpContext.Current.Items["__MySessionVariable"] = new object(); 
} 

它不会储存它在会话中,但它将被存储在HttpContext类的Items字典中,并且在该特定请求期间将可用。由于您是在每次请求时都设置它,因此将它存储到“每会话”字典中会更有意义,顺便说一下,这正是“项目”的全部内容。 :-)

对不起,试图推断你的要求,而不是直接回答你的问题,但我以前遇到过同样的问题,并注意到我需要的不是会话,而是项目属性。

4

您可以使用会话项目中的Application_BeginRequest这样:

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     //Note everything hardcoded, for simplicity! 
     HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("LanguagePref"); 

     if (cookie == null) 
      return; 
     string language = cookie["LanguagePref"]; 

     if (language.Length<2) 
      return; 
     language = language.Substring(0, 2).ToLower(); 
     HttpContext.Current.Items["__SessionLang"] = language; 
     Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language); 

    } 

    protected void Application_AcquireRequestState(object sender, EventArgs e) 
    { 
     HttpContext context = HttpContext.Current; 
     if (context != null && context.Session != null) 
     { 
      context.Session["Lang"] = HttpContext.Current.Items["__SessionLang"]; 
     } 
    }