简体   繁体   中英

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.

Example Global.asax file

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. if you want to make sure no other Controller can Change Value of your variable, but can read it. 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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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