Set session variable in Application_BeginRequest

Daniel Peñalba picture Daniel Peñalba · May 12, 2011 · Viewed 40.9k times · Source

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

Answer

Pankaj picture Pankaj · May 12, 2011

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";
    }
}