Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set session variable in Application_BeginRequest

I'm using ASP.NET MVC and I need to set a session variable at Application_BeginRequest. The problem is that at this point the object HttpContext.Current.Session is always 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());     } } 
like image 624
Daniel Peñalba Avatar asked May 12 '11 11:05

Daniel Peñalba


1 Answers

Try AcquireRequestState in Global.asax. Session is available in this event which fires for each request:

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

Valamas - Suggested Edit:

Used this with MVC 3 successfully and avoids session error.

protected void Application_AcquireRequestState(object sender, EventArgs e) {     HttpContext context = HttpContext.Current;     if (context != null && context.Session != null)     {         context.Session["foo"] = "foo";     } } 
like image 195
Pankaj Avatar answered Sep 28 '22 03:09

Pankaj