在Application_BeginRequest中设置会话变量

42

我正在使用ASP.NET MVC,我需要在Application_BeginRequest中设置一个会话变量。问题是,在此时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());
    }
}

与之相关/类似的重复问题:https://dev59.com/RHRA5IYBdhLWcg3w9y10 - Chris Moschini
3个回答

75
尝试在 Global.asax 中使用 AcquireRequestState。该事件针对每个请求触发,可以在其中访问 Session:
void Application_AcquireRequestState(object sender, EventArgs e)
{
    // Session is Available here
    HttpContext context = HttpContext.Current;
    context.Session["foo"] = "foo";
}

Valamas - 建议的编辑:

我在 MVC 3 中成功地使用了这个方法,并避免了会话错误。

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

4
在这种情况下,我认为Session不是正确的属性。请尝试使用我在答案中展示的context.Current.Items。自页面生命周期开始以来,它不会为空。 - Loudenvier
2
我在MVC3中避免了会话问题。我已经编辑了上面的答案并提出了我的建议。 - Valamas

14

也许你可以改变思路... 或许你可以使用HttpContext类的另一个属性,更具体地说是下面所示的HttpContext.Current.Items

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

它不会在会话中存储,但它将存储在HttpContext类的Items字典中,并且在那个特定请求的持续时间内可用。由于您正在每个请求中设置它,将其存储到“每个会话”字典中真的更有意义,这恰好是Items的作用。

很抱歉没有直接回答您的问题,而是试图推断您的要求,但我以前也遇到过同样的问题,并注意到我所需要的不是Session,而是Items属性。


4
您可以在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"];
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接