ASP.NET:整个站点都可以访问的变量

Bil*_*ill 11 c# asp.net visual-studio

我是ASP .NET的新手,我正在尝试使用C#在Visual Studio中设置一个网站.

我的背景是PHP.在该语言中,如果我希望每个页面都可以访问变量,只需将其放在包含文件中即可.

有没有类似于C#和ASP .NET的东西?有一个site.master页面,但我不知道如何从页面内容访问它的变量.提前致谢.

Kar*_*oll 21

你有几个不同的选择:


会话变量 会话变量存储在服务器的内存中,供每个用户使用,并且可以根据需要随时读取和写入.这些仅限于每个用户,因此如果您想为所有用户保留单个变量,那么这不是可行的方法.

用法:

Session["MyVariable"] = 5;
int myVariable = (int)Session["MyVariable"]; //Don't forget to check for null references!
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以在session_start事件处理程序下的global.asax文件中设置用户的会话变量.


应用程序/缓存变量 任何用户都可以访问应用程序和缓存变量,并且可以根据需要进行获取/设置.两者之间的唯一区别是Cache变量可以过期,这使得它们对于诸如数据库查询结果之类的东西很有用,这些结果可以在它们过期之前保留一段时间.用法:

Application["MyVariable"] = 5;
int myVariable = (int)Application["MyVariable"]; //Don't forget to check for null references!
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以在application_start事件处理程序中的global.asax文件中设置应用程序变量.


Web.Config 这可能是在应用程序中存储常量的首选方法,因为它们存储为"应用程序设置"并在您的web.config文件中根据需要进行更改,而无需重新编译您的站点.应用程序设置<appsettings>使用以下语法存储在文件的区域中:

<appSettings>
  <add key="MyVariable" value="5" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

Web.config值应该在代码中被认为是只读的,并且可以使用页面中的以下代码进行访问:

int myVariable = (int)System.Configuration.ConfigurationSettings.AppSettings["MyVariable"];
Run Code Online (Sandbox Code Playgroud)

静态变量 或者,您可以创建一个包含静态属性的类来保存您的变量,如下所示:

public class SiteVariables
{
    private static _myVariable = 0;
    public static int MyVariable
    {
        get { return _myVariable; }
        set { _myVariable = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样访问它:

int myVar = SiteVariables.MyVariable;
Run Code Online (Sandbox Code Playgroud)

我实际上在我的代码中使用了后两种解决方案的组合.我将我的设置保存在我的web.config文件中,然后创建一个名为的类ApplicationSettings,在需要时使用静态属性从web.config中读取值.

希望这可以帮助