正确使用global.asax中的变量

本文关键字:变量 asax global | 更新日期: 2023-09-27 18:18:32

我有一个简单的全局。一个在启动时运行一些代码并在变量中存储句柄的文件。我想从项目中的其他文件访问该变量。这是我的global.asax:

<%@ Application Language="C#" %>
<script runat="server">
    static JustTesting justTesting;
    static public JustTesting JustTesting { get { return justTesting ; } }
    void Application_Start(object sender, EventArgs e) 
    {
        //my code here
    }
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown
    }
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs
    }
</script>

当我想使用这个变量时…

ASP.global_asax.JustTesting

…这是有效的,但我相信一定有一个更优雅的方式来调用它,而不是必须添加ASP.global_asax.所有的时间。

正确使用global.asax中的变量

您可以使用Application对象

阅读:

var x = Application["x"];
写作:

Application.Lock();
Application["x"] = "value";
Application.UnLock();

参考:http://msdn.microsoft.com/en-us/library/94xkskdf (v =应用程序). aspx

你也可以创建自己的类,它应该是线程安全的