Dan*_*lba 37 asp.net asp.net-mvc global-asax asp.net-mvc-3 asp.net-mvc-2
我正在使用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());
}
}
Run Code Online (Sandbox Code Playgroud)
Pan*_*kaj 70
尝试Global.asax中的AcquireRequestState.此事件中的会话可针对每个请求触发:
void Application_AcquireRequestState(object sender, EventArgs e)
{
// Session is Available here
HttpContext context = HttpContext.Current;
context.Session["foo"] = "foo";
}
Run Code Online (Sandbox Code Playgroud)
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";
}
}
Run Code Online (Sandbox Code Playgroud)
Lou*_*ier 13
也许你可以改变范式......也许你可以使用HttpContext该类的另一个属性,更具体地说HttpContext.Current.Items如下所示:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext.Current.Items["__MySessionVariable"] = new object();
}
Run Code Online (Sandbox Code Playgroud)
它不会将它存储在会话中,但它将存储在HttpContext类的Items字典中,并将在该特定请求的持续时间内可用.由于您是在每次请求时设置它,因此将它存储到"每个会话"字典中会更有意义,顺便说一句,这就是项目的全部内容.:-)
很抱歉尝试推断您的要求,而不是直接回答您的问题,但我之前遇到过同样的问题,并注意到我需要的不是Session,而是Items属性.
| 归档时间: |
|
| 查看次数: |
38808 次 |
| 最近记录: |