在Application_BeginRequest中设置会话variables

我正在使用ASP.NET MVC,我需要在Application_BeginRequest设置一个会话variables。 问题是,在这一点上对象HttpContext.Current.Session始终为null

 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()); } } 

尝试Global.asax中的AcquireRequestState。 会话可在此事件中触发每个请求:

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

Valamas – build议编辑:

与MVC 3成功使用,并避免会话错误。

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

也许你可以改变范例…也许你可以使用HttpContext类的另一个属性,更具体的HttpContext.Current.Items如下所示:

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

它不会将其存储在会话中,而是存储在HttpContext类的Items字典中,并在该特定请求的持续时间内可用。 既然你是按照每一个请求来设置它的,那么将它存储到“每个会话”字典中是非常有意义的,顺便说一下,这正是“物品”所关心的。 🙂

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

你可以这样使用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"]; } }