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());
}
}
Try AcquireRequestState in Global.asax. Session is available in this event which fires for each request:
Valamas - Suggested Edit:
Used this with MVC 3 successfully and avoids session error.
Maybe you could change the paradigm... Perhaps you can use another property of the
HttpContext
class, more specificallyHttpContext.Current.Items
as shown below:It won't store it on the session, but it will be stored on the Items dictionary of the HttpContext class and will be available for the duration of that specific request. Since you're setting it at every request, it would really make more sense to store it into a "per session" dictionary which, incidentally, is exactly what the Items is all about. :-)
Sorry to try to infer your requirements instead of answering your question directly, but I've faced this same problem before and noticed that what I needed was not the Session at all, but the Items property instead.
You can use the session items in Application_BeginRequest this way: