2

我们可以将应用程序级别的字符串存储在 global.asax 文件中,例如: Global asax:

void Application_Start(object sender, EventArgs e) 
    {
        Application.Lock();
        Application["msg"] = "";            
        Application.UnLock();        
    }

然后在页面中我们得到“msg”变量: a.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
 {
        string msg = (string)Application["msg"];
        //manipulating msg..
 }

但是,我想将对象列表存储为应用程序级变量而不是字符串 msg。我试过这个: Global.asax:

void Application_Start(object sender, EventArgs e) 
    {
        Application.Lock();
        List<MyClassName> myobjects= new List<MyClassName>();      
        Application.UnLock();        
    }

a.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
    {
        //here I want to get myobjects from the global.asax and manipulate with it..
    }

那么,如何将 List myobjects 存储为 global.asax 中的应用程序级变量并使用它呢?

此外,我还有一个问题: 当 global.asax 中的全局变量发生更改时,如何向客户端(浏览器)发送任何通知?

4

1 回答 1

1

一种方法是将其存储到缓存中:

using System.Web.Caching;    

protected void Application_Start()
{
   ...
   List<MyClassName> myobjects = new List<MyClassName>();
   HttpContext.Current.Cache["List"] = myobjects;
}

然后访问/操作它:

using System.Web.Caching;

var myobjects =  (List<MyClassName>)HttpContext.Cache["List"];
//Changes to myobjects
...
HttpContext.Cache["List"] = myobjects;
于 2012-10-12T11:24:44.737 回答