如何在任何页面上存储静态类对象以供调用

本文关键字:对象 静态类 调用 存储 任何页 | 更新日期: 2023-09-27 18:32:20

我想将静态值存储在类中,以便以后在网络上的任何页面上使用。所有用户的值都相同。

Page_Init:从全局变量各自的源中检索全局变量,并将它们分配给 GlobalStaticVariables 类中类中的静态对象。

我调用以像这样从母版页设置静态值

protected void Page_Init(object sender, EventArgs e)
{
    Web.StartUp.SetGlobalStaticVariables(this.Page);
}
///Removed most objects for the sake of brevity
public static Info.GlobalStaticVariables SetGlobalStaticVariables(object _this)
{
    Info.GlobalStaticVariables.Some_StringValue = ConfigurationManager.AppSettings["Some_StringValue"].ToString();
    Info.GlobalStaticVariables.Database.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    Info.GlobalStaticVariables.IIS.DomainName = ((Page)_this).Request.Url.Host;
}
///Removed most objects for the sake of brevity
public class Info
{
    public class GlobalStaticVariables
    {
        public static string Some_StringValue { get; set; }
        public class Database
        {
            public static string ConnectionString { get; set; }
        }
        public class Ldap
        {
            public static List<string> ServerList { get; set; }
        }
    }
}

我认为我应该首先查看会话对象是否存在,然后创建如果不存在,因为我已经读到有时静态值可能会由于 appPool 回收等而丢失。

我想我应该从 MasterPage 执行此操作,因为我必须引用"会话",但我不知道如何将 Page 对象传递给类文件中的属性。

我在母版页中使用以下方法来存储当前用户,因此我认为我可以对全局变量做类似的事情。到目前为止,我还没有成功。

public MyClass.Users.CurrentUser GetSetCurrentUser
{
    get
    {
        if (Session["CurrentUser"] == null) GetSetCurrentUser = new MyClass.Users.CurrentUser();
        return (MyClass.Users.CurrentUser)Session["CurrentUser"];
    }
    set { Session.Add("CurrentUser", value); }
}

对于前面,我还必须将以下内容添加到想要引用 GetSetCurrentUser 属性的每个页面 (Master.GetSetCurrentUser ),但如果可能的话,我宁愿避免这种情况。

<%@ MasterType VirtualPath="~/mp.Master" %>

不幸的是,当我尝试使用全局静态变量进行相同的操作时,除了 .等于。GetHashCode, .GetType 和 .到字符串。

我希望能够从任何页面调用属性 GlobalStaticVariables,以便轻松访问它的静态值。

也许我的思维过程在尝试这样做时是有缺陷的,但我想不出另一种方法。也许我需要暂时离开这里,享受假期,但我不能,我正在执行一项任务。:-)

谢谢你的时间和建议。

如何在任何页面上存储静态类对象以供调用

您正在寻找 HttpApplicationState,该

HttpApplicationState 在您的页面中可用,该属性包含Application属性Context属性。

如何使用它:

void Page_Load(object sender, EventArgs e) 
{
     var last = Context.Application["lastActivity"];
     lblLastActivity.Text = last == null?"(none)": ((DateTime) last).ToString();
     Context.Application["lastActivity"] = DateTime.Now;
}

另一种选择是使用缓存,其工作原理类似,但存储在缓存中的对象可以从缓存中删除(以释放内存)。在这种情况下,您应该能够重新加载对象。