Sun*_*oot 78
从技术上讲,项目中任何地方的任何静态变量或属性都将是一个全局变量,例如
public static class MyGlobalVariables
{
public static string MyGlobalString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但正如@SLaks所说,如果处理不当,他们可能"潜在地"成为不好的做法并且很危险.例如,在上面的示例中,您将有多个请求(线程)尝试访问同一属性,如果它是复杂类型或集合,则可能是一个问题,您必须实现某种形式的锁定.
aba*_*hev 47
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
GvS*_*GvS 24
你可以把它们放在应用程序中:
Application["GlobalVar"] = 1234;
Run Code Online (Sandbox Code Playgroud)
它们仅在当前IIS /虚拟应用程序中是全局的.这意味着,在webfarm上,它们是服务器的本地,并且位于作为应用程序根目录的虚拟目录中.
Yas*_*ani 18
对于非静态变量,我通过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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中:
namespace MvcWebApplication.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View(HttpContext.Application["LicenseFile"] as string);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样我们就可以在ASP.NET MVC中拥有全局变量:)
注意:如果您的对象不是字符串,只需写:
return View(HttpContext.Application["X"] as yourType);
Run Code Online (Sandbox Code Playgroud)
您还可以使用静态类,例如Config类或沿着这些行的某些东西......
public static class Config
{
public static readonly string SomeValue = "blah";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
178971 次 |
| 最近记录: |