【问题标题】:How to handle application start event in ASP.NET module如何在 ASP.NET 模块中处理应用程序启动事件
【发布时间】:2010-06-25 15:00:30
【问题描述】:

我正在编写一个 asp.net HTTP 模块,它需要从本地文件(比如 config.xml 存储在应用程序根目录中)读取配置数据一次,然后根据配置执行一些处理传入的请求。

由于 Asp.NET 模块中没有可用的 Application_Start/Application_init 挂钩,因此处理该场景的最佳方法是什么。我试图避免每次请求到来时读取配置文件。理想情况下,我想在应用程序启动时读取配置文件。

我只需要在 http 模块中编写代码,不想使用 Global.asax

【问题讨论】:

  • 为什么不使用静态变量呢?静态意味着所有会话。
  • 静态类对象仅在首次访问时初始化,而不是在 IIS 应用程序池启动时初始化。如果必须在启动时立即初始化,则 Application_Start 处理程序会更好。

标签: c# asp.net httpmodule


【解决方案1】:

我会选择一个简单的财产,像这样......

public MyConfig Config
{
    get
    {
        MyConfig _config = Application["MyConfig"] as MyConfig;
        if (_config == null)
        {
            _config = new MyConfig(...);
            Application["MyConfig"] = _config;
        }
        return _config;
    }
}

这样您只需通过属性从 Config 访问您需要的任何内容...

int someValue = Config.SomeValue;

如果它还没有被加载到应用程序对象中

如果您需要基于每个用户而不是全局的配置,那么只需使用 Session["MyConfig"] 而不是 Application["MyConfig"]

【讨论】:

    【解决方案2】:

    不确定这是否可行,但您可以在模块的init method 中实现它。

    【讨论】:

    • 我刚试过。似乎 Init 方法中的变量/对象等在 HTTPmodule“可挂钩”事件中不可用,如 Application_BeginRequest 等
    【解决方案3】:

    在您的 httpmodule 的 init 方法中,您可以连接到上下文中的事件。

    例如:

    public void Init(HttpApplication context)
        {
    
            context.PostRequestHandlerExecute += (sender, e) =>
            {
                Page p = context.Context.Handler as Page;
                if (p != null)
                {
                ///Code here    
                }
            };
        }
    

    【讨论】:

    • 刚刚注意到没有要连接的开始事件,为什么不在您的 http 模块的 init 方法中填充数据...
    【解决方案4】:
    public SomeHttpModule : IHttpModule
    {    
        private static readonly Configuration Configuration = 
                ConigurationReader.Read();    
    }
    

    【讨论】:

      【解决方案5】:

      静态变量成功了。如果有人感兴趣,这里是代码 -

      static string test; 
              public void Init(HttpApplication application)
              {
      
      
                  application.BeginRequest +=(new EventHandler(this.Application_BeginRequest));
                  test = "hi"; 
                  application.EndRequest +=(new EventHandler(this.Application_EndRequest));
      
      
              }
             private void Application_BeginRequest(Object source,EventArgs e)
              {
                  {
                      HttpApplication application = (HttpApplication)source ;
                      HttpContext context = application.Context;
                      context.Response.Write(test);
                  }
      
      
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-09
        • 1970-01-01
        • 2013-08-28
        • 1970-01-01
        • 2018-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多