Set session variable in Application_BeginRequest

42,668

Solution 1

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

Solution 2

Maybe you could change the paradigm... Perhaps you can use another property of the HttpContext class, more specifically HttpContext.Current.Items as shown below:

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

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.

Solution 3

You can use the session items in Application_BeginRequest this way:

    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"];
        }
    }
Share:
42,668
Daniel Peñalba
Author by

Daniel Peñalba

Software Engineer at Unity Technologies, Valladolid, Spain. Currently developing gmaster, Plastic SCM and SemanticMerge. Areas: C# GUI development Winforms and WPF expert ASP .NET Core Multiplatform UI development with Mono (Linux and OSX, GTK# and MonoMac) Eclipse plugin, Java Automated testing, NUnit, Moq, PNUnit and TestComplete Email: dpenalba[AT]codicesoftware[DOT]com I play the guitar at Sharon Bates, the greatest Spanish rock band.

Updated on July 09, 2022

Comments

  • Daniel Peñalba
    Daniel Peñalba almost 2 years

    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());
        }
    }
    
  • Elan Hasson
    Elan Hasson about 12 years
    This is exactly what I needed.
  • Loudenvier
    Loudenvier over 11 years
    I think that in this case the Session is not the right property to use anyway. Try the context.Current.Items as I've shown in my answer. It won't be null since the start of the page life-cycle.
  • Valamas
    Valamas almost 11 years
    I avoided the session issue in MVC3. I have edited the answer above with my suggestion.