【问题标题】:ASP.NET MVC HttpContext.Session objectASP.NET MVC HttpContext.Session 对象
【发布时间】:2010-11-18 08:53:48
【问题描述】:

我有一个问题。我在我的项目中构建了自定义类,其中包含公共静态属性 ctx 和 assingn HttpContext.Current 对象。在运行时该属性似乎引用 HttpContext 对象,但 ctx.Session 类为空。当我调试我的应用程序时,表达式的左侧(ctx)与右侧(HttpContext.Current)不完全相同。为什么会这样?

问候

【问题讨论】:

    标签: asp.net-mvc httpcontext


    【解决方案1】:

    HttpContext.Current 是仅针对该请求的单例。通过将 HttpContext.Current 分配给静态变量,您将将此 HttpContext.Current 共享给整个范围,这可能是不正确的。

    Session 是每个用户的对象,而 static 是应用程序范围的对象。明智地使用静态。

    【讨论】:

      【解决方案2】:

      我会做这样的事情。

      1- 提供当前 httpcontext 的静态类(例如:ContextFactory)。如果它有 HttpContext.Current,则提供该值,如果没有,则提供分配的上下文。在你的情况下,new Mock<HttpContextBase>();

      public static class ContextFactory
      {
          private static HttpContextBase current = null;
      
          public static HttpContextBase Current
          {
              get { return current ?? HttpContext.Current; }
              set { current = value; }
          }
      }
      

      2- 然后我将代码 UserSess 更改为

      public static class UserSess 
      {
          public static UserID
          {
              get { return ContextFactory.Current.Session["UserID"]; }
              set { ContextFactory.Current.Session["UserID"] = value; } 
          }
         //... 
      }
      

      真诚的

      【讨论】:

      • 不要将会话(=每个用户不同)存储在静态变量中(=每个用户都相同)!
      • 如您所见,会话不会存储在静态类中,除非用户设置它(必须在测试中完成)。如果未设置,它将返回当前的 http 上下文和正确的会话。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 2017-12-31
      • 1970-01-01
      相关资源
      最近更新 更多