【问题标题】:ASP.NET MVC How to access a property in the Global.asax file from the Controller?ASP.NET MVC 如何从控制器访问 Global.asax 文件中的属性?
【发布时间】:2011-04-01 11:52:42
【问题描述】:

在 Global.asax 文件中,我管理一些线程,并且 - 从控制器 - 我需要调用一个线程的事件。是否可以访问该线程?

【问题讨论】:

    标签: asp.net-mvc-3 controller global-asax


    【解决方案1】:

    您可以使用应用程序状态来存储一些将在应用程序的所有用户之间共享的对象:

    protected void Application_Start()
    {
        Application["foo"] = "bar";
        ...
    }
    

    在您的控制器内部,您可以访问此属性:

    public ActionResult Index()
    {
        var foo = HttpContext.Application["foo"] as string;
        ...
    }
    

    【讨论】:

      【解决方案2】:

      如果它是任何其他类型的对象(如字符串),您可以这样做,因为您需要在 Global.asax 中将属性声明为静态以使其可用于应用程序的其余部分:

      public class Application : HttpApplication
      {
          // This is the class declared in Global.asax
      
          // Your route definitions and initializations are also in here
      
          public static string MyProperty { get; set; }
      }
      

      这将可供应用程序的其余部分使用。您可以通过以下方式调用:

      public ActionResult MyAction()
      {
          var bla = Application.MyProperty;
      }
      

      也就是说,我认为您不想以这种方式为应用程序的其余部分提供Thread

      【讨论】:

      • 太棒了。我喜欢这个分配比将它存储为索引 +1 更好
      猜你喜欢
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      相关资源
      最近更新 更多