【发布时间】:2010-11-18 08:53:48
【问题描述】:
我有一个问题。我在我的项目中构建了自定义类,其中包含公共静态属性 ctx 和 assingn HttpContext.Current 对象。在运行时该属性似乎引用 HttpContext 对象,但 ctx.Session 类为空。当我调试我的应用程序时,表达式的左侧(ctx)与右侧(HttpContext.Current)不完全相同。为什么会这样?
问候
【问题讨论】:
我有一个问题。我在我的项目中构建了自定义类,其中包含公共静态属性 ctx 和 assingn HttpContext.Current 对象。在运行时该属性似乎引用 HttpContext 对象,但 ctx.Session 类为空。当我调试我的应用程序时,表达式的左侧(ctx)与右侧(HttpContext.Current)不完全相同。为什么会这样?
问候
【问题讨论】:
HttpContext.Current 是仅针对该请求的单例。通过将 HttpContext.Current 分配给静态变量,您将将此 HttpContext.Current 共享给整个范围,这可能是不正确的。
Session 是每个用户的对象,而 static 是应用程序范围的对象。明智地使用静态。
【讨论】:
我会做这样的事情。
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; }
}
//...
}
真诚的
【讨论】: