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

本文关键字:全局变量 ASP Net MVC 访问 | 更新日期: 2024-10-20 10:51:55

由于我正在处理的项目的性质,我希望在Global.asax文件中有一个私有变量可以从我的控制器访问。

示例Global.asax文件

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

控制器示例

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

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

我会这样做:

public class BaseController : Controller
    {
       .....
       protected string SomeString { get; set; }
       ....
    }
public class HomeController : BaseController
{
   public ActionResult Index()
    {
        string theString = SomeString;
    }
}

我在猜测你为什么想要"Private Global"。Private的作用域仅在类中具有。如果你想确保没有其他控制器可以更改你的变量的值,但可以读取它。你可以将其设为常量或私有集。

Public Get but Private set example

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

尽管如果试图限制只有您的程序集可以访问变量,而不能访问其他程序集(这似乎不太可能,因为您正在处理MVC项目)。您应该尝试内部,例如

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";
            }
        }

我不建议你这样做,最好你可以创建静态类和静态属性。