简体   繁体   English

在ASP.Net MVC中访问私有全局变量

[英]Access a Private Global variable in ASP.Net MVC

Due to the nature of a project im working on, I would like to have a private variable in the Global.asax file accessible from my controllers. 由于正在进行的项目的性质,我希望在Global.asax文件中有一个私有变量,可从我的控制器访问。

Example Global.asax file 示例Global.asax文件

public class MvcApplication : System.Web.HttpApplication
{
    public string SomeString { get; set; }
}

Example Controller 控制器示例

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string theString = // How to access the SomeString from Global.asax;
    }
}

I would do it like this: 我会这样做:

public class BaseController : Controller
    {
       .....
       protected string SomeString { get; set; }
       ....
    }

public class HomeController : BaseController
{
   public ActionResult Index()
    {
        string theString = SomeString;
    }
}

I am trying to guess why will you want "Private Global". 我试图猜测您为什么要“全球私有”。 The scope of Private is only with in the class. Private的范围仅在该类中。 if you want to make sure no other Controller can Change Value of your variable, but can read it. 如果要确保没有其他Controller可以更改变量的值,但是可以读取它。 You can either make it Constant or Private Set. 您可以将其设为“常数”或“专用集”。

Public Get but Private set example. 公开获取但私有设置示例。

public class MvcApplication : System.Web.HttpApplication
{
    public string SomeString { get; private set; }
}

Though if trying to restrict that only your assembly can access the variable but no other assembly (which seems unlikely as u working on MVC project). 虽然如果试图限制只有您的程序集可以访问变量,但不能访问其他程序集(这在您从事MVC项目时似乎不太可能)。 You should try internal eg, 您应该尝试内部例如

public class MvcApplication : System.Web.HttpApplication
{
    internal string SomeString { get; private set; }
}
public class MvcApplication : System.Web.HttpApplication
        {
            public string SomeString { get; set; }
        }


        public class HomeController : Controller
        {
            public ActionResult Index()
            {

    MvcApplication mvc = new MvcApplication();
                mvc.SomeString = "Test1";
            }
        }

I will not suggest you do this, Its better you can create static class and static property. 我不建议您这样做,最好创建静态类和静态属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM