asp.net – 在Application_BeginRequest中设置会话变量

前端之家收集整理的这篇文章主要介绍了asp.net – 在Application_BeginRequest中设置会话变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用ASP.NET MVC,我需要在Application_BeginRequest设置一个会话变量。问题是,在这一点对象HttpContext.Current.Session总是null。
  1. protected void Application_BeginRequest(Object sender,EventArgs e)
  2. {
  3. if (HttpContext.Current.Session != null)
  4. {
  5. //this code is never executed,current session is always null
  6. HttpContext.Current.Session.Add("__MySessionVariable",new object());
  7. }
  8. }

解决方法

在Global.asax中尝试AcquireRequestState。会话在此事件中可用,针对每个请求触发:
  1. void Application_AcquireRequestState(object sender,EventArgs e)
  2. {
  3. // Session is Available here
  4. HttpContext context = HttpContext.Current;
  5. context.Session["foo"] = "foo";
  6. }

Valamas – 建议修改

与MVC 3成功地使用它,并避免会话错误

  1. protected void Application_AcquireRequestState(object sender,EventArgs e)
  2. {
  3. HttpContext context = HttpContext.Current;
  4. if (context != null && context.Session != null)
  5. {
  6. context.Session["foo"] = "foo";
  7. }
  8. }

猜你在找的asp.Net相关文章