2011-05-12 144 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"]; 
     } 
    }