ASP.NET MVC HttpContext.Session 对象
我有一个问题。我在项目中构建了自定义类,其中包含公共静态属性 ctx 并为其分配 HttpContext.Current 对象。在运行时该属性似乎引用 HttpContext 对象,但 ctx.Session 类为 null。当我调试我的应用程序时,表达式(ctx)的左侧与右侧(HttpContext.Current)不完全相同。为什么会发生这种情况?
格雷廷斯
I have a question. I've built custom class in my project that contains public static property ctx and assingn HttpContext.Current object to it. In runtime that property seem to reference HttpContext object, but ctx.Session class is null. When i debug my app the left side of an expression (ctx) is not exactly the same as right side (HttpContext.Current). why this is happening?
Grettings
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HttpContext.Current 是仅用于该请求的单例。通过将 HttpContext.Current 分配给静态变量,您将将此 HttpContext.Current 共享给整个范围,这可能不正确。
Session 是每个用户的对象,而 static 是应用程序范围的对象。明智地使用静态。
HttpContext.Current is a singleton only for that request. By assigning the HttpContext.Current to a static variable you would be sharing this HttpContext.Current to an entire scope, which may not be right.
Session is a per user object while, static is an application wide object. Use static wisely.
我会做这样的事情。
1- 提供当前 httpcontext 的静态类(例如:
ContextFactory
)。如果它有 HttpContext.Current,则提供该值,如果没有,则提供分配的上下文。在你的情况下,new Mock();
2-然后我将代码 UserSess 更改为
真诚的
What I would do would be something like this.
1- a static class (ex:
ContextFactory
) which provides current httpcontext. If it has HttpContext.Current, then is provides that value, if not then it provides an assigned context. In your case,new Mock<HttpContextBase>();
2- Then I alter the code UserSess to
sincerely