【问题标题】:Having problems accessing Public Static variable in Global.asax.cs using HttpContext.Current (C#)使用 HttpContext.Current (C#) 访问 Global.asax.cs 中的公共静态变量时出现问题
【发布时间】:2013-04-12 20:02:16
【问题描述】:

在一个 Web 项目中,我在 global.asax.cs 中定义了一个需要在整个应用程序中访问的公共静态变量(Store)。

public class Global : HttpApplication
{
    public static UserDataStore Store;

    void Application_Start(object sender, EventArgs e)
    {
        Store = new UserDataStore();
        Store.CurrentUsers = new Hashtable();
    }

    void Session_Start(object sender, EventArgs e)
    {
        if (!Store.UserExists(HttpContext.Current.Session.SessionID))
            Store.AddUser(HttpContext.Current.Session.SessionID, "StubUser");
    }
}

我需要在另一个无法引用 Web 项目(并且它是全局对象)的项目中访问它,因为它会导致循环引用。

我的解决方法是尝试使用 HttpApplication 对象检索 Store:

UserDataStore udStore = (UserDataStore) HttpContext.Current.Application["Store"];

这会编译,但返回一个空对象。

我已经对谷歌视而不见,试图找到其他类似的例子,但我发现的大部分内容都支持以下两种方法之一:

  1. 使用 Application[""] 变量,这是次优的,用于根据本文的经典 ASP 兼容性:http://support.microsoft.com/kb/312607
  2. 通过 Web 项目的 Global 类访问它,这不是我们当前设置中的选项。

这似乎应该是可能的,所以希望我错过了一些愚蠢的东西。

您能提供的任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 该范围内的 Application[""] 不应该与 HttpContext.Current.Application 相同吗?你在哪里分配它?即:HttpContext.Current.Application["Store"] = Store.

标签: c# static global-asax


【解决方案1】:

使用共享数据创建第三个(库)项目,并从其他两个项目中引用它。

【讨论】:

  • 我确实将 UserDataStore 类移到了第三个项目中,因为它位于 Web 项目中。但是我们仍然想使用 Global.asax.cs 中的 Application/Session Start/End 事件。 Slo UserDataStore 对象的存储应该保留在那里。
  • @Chris Cline:为什么?你似乎对自己施加了一种奇怪的约束。例如,您可以在 UserDataStore 本身上拥有一个静态属性,然后简单地从 global.asax 访问它。仅仅因为您在 global.asax 中使用它并不意味着您也必须在其中定义持有字段。
  • 我能说什么?我喜欢奇怪的约束。但说真的,我采纳了您的建议并相应地重构了我们的代码。到目前为止,它似乎工作顺利。谢谢!
【解决方案2】:

Application[""] 应该与 HttpContext.Current.Application 相同。你记得添加那个值吗?您可以从 Application_Start 调用其中任何一个。

Application["Store"] = Store 

HttpContext.Current.Application["Store"] = Store

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多