在设置的Application_BeginRequest会话变量 [英] Set session variable in Application_BeginRequest

查看:729
本文介绍了在设置的Application_BeginRequest会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC和我需要设置为的Application_BeginRequest 会话变量。问题是,在这一点上对象 HttpContext.Current.Session 总是

 保护无效的Application_BeginRequest(对象发件人,EventArgs的发送)
{
    如果(HttpContext.Current.Session!= NULL)
    {
        //这个code从不执行,当前会话中始终为null
        HttpContext.Current.Session.Add(__ MySessionVariable,新的对象());
    }
}


解决方案

尝试的AcquireRequestState在Global.asax中。会议可在这一事件,激发每个请求:

 无效Application_AcquireRequestState(对象发件人,EventArgs的发送)
{
    //会话可以在这里找到
    HttpContext的背景下= HttpContext.Current;
    context.Session [富] =富;
}

Valamas - 建议编辑:

使用MVC 3中成功地使用这个,避免会话错误。

 保护无效Application_AcquireRequestState(对象发件人,EventArgs的发送)
{
    HttpContext的背景下= HttpContext.Current;
    如果(上下文= NULL&放大器;!&安培;!context.Session = NULL)
    {
        context.Session [富] =富;
    }
}

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:

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

这篇关于在设置的Application_BeginRequest会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆