ASP.NET MVC HttpContext.Session 对象

发布于 2024-10-03 11:04:14 字数 197 浏览 4 评论 0原文

我有一个问题。我在项目中构建了自定义类,其中包含公共静态属性 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笔芯 2024-10-10 11:04:14

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.

兲鉂ぱ嘚淚 2024-10-10 11:04:14

我会做这样的事情。

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

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; } 
    }
   //... 
}

真诚的

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>();

public static class ContextFactory
{
    private static HttpContextBase current = null;

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

2- Then I alter the code UserSess to

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

sincerely

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文