如何在ASP.NET MVC中声明全局变量?
发布于 2011-02-25 23:03:02
public static class GlobalVariables
{
// readonly variable
public static string Foo
{
get
{
return "foo";
}
}
// read-write variable
public static string Bar
{
get
{
return HttpContext.Current.Application["Bar"] as string;
}
set
{
HttpContext.Current.Application["Bar"] = value;
}
}
}
发布于 2011-02-25 23:35:35
从技术上讲,类上的任何静态变量或属性,在项目中的任何位置都将是全局变量,例如
public static class MyGlobalVariables
{
public static string MyGlobalString { get; set; }
}
但正如@SLaks所说,如果处理不当,它们可能是“潜在的”糟糕的做法和危险的。例如,在上面的示例中,您将有多个请求(线程)试图访问同一属性,如果它是复杂类型或集合,这可能是一个问题,您必须实现某种形式的锁定。
发布于 2011-02-25 22:51:56
您可以将它们放入应用程序中:
Application["GlobalVar"] = 1234;
它们仅在当前IIS /虚拟应用程序中是全局的。这意味着,在网络场中,它们位于服务器本地,并且位于作为应用程序根的虚拟目录中。
https://stackoverflow.com/questions/5118610
复制相似问题