如何在ASP.NET MVC中声明全局变量?
Answers:
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;
}
}
}
从技术上讲,项目中任何位置上类的任何静态变量或Property都将是Global变量,例如
public static class MyGlobalVariables
{
public static string MyGlobalString { get; set; }
}
但是,正如@SLaks所说,如果处理不当,它们可能“是不好的做法,并且很危险”。例如,在上面的示例中,您将有多个请求(线程)试图访问相同的Property,如果它是复杂类型或集合,则可能是个问题,您将必须实现某种形式的锁定。
对于非静态变量,我通过Application类字典对其进行了分类,如下所示:
在Global.asax.ac:
namespace MvcWebApplication
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
private string _licensefile; // the global private variable
internal string LicenseFile // the global controlled variable
{
get
{
if (String.IsNullOrEmpty(_licensefile))
{
string tempMylFile = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(LDLL.License)).Location), "License.l");
if (!File.Exists(tempMylFile))
File.Copy(Server.MapPath("~/Content/license/License.l"),
tempMylFile,
true);
_licensefile = tempMylFile;
}
return _licensefile;
}
}
protected void Application_Start()
{
Application["LicenseFile"] = LicenseFile;// the global variable's bed
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
在控制器中:
namespace MvcWebApplication.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View(HttpContext.Application["LicenseFile"] as string);
}
}
}
这样,我们可以在ASP.NET MVC中使用全局变量:)
注意:如果您的对象不是字符串,只需编写:
return View(HttpContext.Application["X"] as yourType);
Application
课堂字典。”
该钢是远离热,但我结合@ abatishchev与从应答解决方案这篇文章,并得到了这个结果。希望它有用:
public static class GlobalVars
{
private const string GlobalKey = "AllMyVars";
static GlobalVars()
{
Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;
if (table == null)
{
table = new Hashtable();
HttpContext.Current.Application[GlobalKey] = table;
}
}
public static Hashtable Vars
{
get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
}
public static IEnumerable<SomeClass> SomeCollection
{
get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
set { WriteVar("SomeCollection", value); }
}
internal static DateTime SomeDate
{
get { return (DateTime)GetVar("SomeDate"); }
set { WriteVar("SomeDate", value); }
}
private static object GetVar(string varName)
{
if (Vars.ContainsKey(varName))
{
return Vars[varName];
}
return null;
}
private static void WriteVar(string varName, object value)
{
if (value == null)
{
if (Vars.ContainsKey(varName))
{
Vars.Remove(varName);
}
return;
}
if (Vars[varName] == null)
{
Vars.Add(varName, value);
}
else
{
Vars[varName] = value;
}
}
}