在Application_BeginRequest中设置会话变量

时间:2011-05-12 11:31:03

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 global-asax

我正在使用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());
    }
}

3 个答案:

答案 0 :(得分:67)

在Global.asax中尝试AcquireRequestState。此事件中的会话可以针对每个请求触发:

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

答案 1 :(得分:12)

也许你可以改变范例......也许你可以使用HttpContext类的另一个属性,更具体地说是HttpContext.Current.Items,如下所示:

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

它不会将其存储在会话中,但它将存储在HttpContext类的Items字典中,并且在特定请求的持续时间内可用。由于您是在每次请求时设置它,因此将它存储到“每个会话”字典中会更有意义,顺便说一句,这就是项目的全部内容。 : - )

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

答案 2 :(得分: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"];
        }
    }