【问题标题】:Why is there no way to unbind an HttpApplication event handler out of IHttpModule initialization scope为什么无法将 HttpApplication 事件处理程序解除绑定到 IHttpModule 初始化范围之外
【发布时间】:2011-04-29 20:35:05
【问题描述】:

假设我们只想在 Web 应用程序启动后和 Web 请求期间执行某个操作一次或几次。

public class WebApp : HttpApplication
{
    public override void Init()
    {
        base.Init();

        this.BeginRequest += new EventHandler(this.OnFirstBeginRequest);
    }

    private void OnFirstBeginRequest(object sender, EventArgs e)
    {
        // do some action and if everything is OK, unbind this handler,
        // because we need it executed only once at the first web request
        this.BeginRequest -= new EventHandler(this.OnFirstBeginRequest);
    }
}

会抛出以下异常:

事件处理程序只能绑定到 期间的 HttpApplication 事件 IHttpModule 初始化。

【问题讨论】:

标签: c# asp.net binding ihttpmodule httpapplication


【解决方案1】:

HttpApplication 实例中使用事件处理程序在对应用程序的第一次请求时执行一些代码是没有意义的,因为每次创建新的HttpApplication 实例时,它都会重新绑定这些事件和事件处理程序中的代码将再次运行。

多个HttpApplication 实例由 ASP.NET 工作进程创建。出于性能目的,它们被汇集在一起​​,但对于您的网络应用程序,HttpApplication 服务请求肯定可以有不止一个实例。

Here's a pretty good article on the subject.

【讨论】:

  • 是的,正是由于这个原因,我需要解除绑定一个事件处理程序,该处理程序在完成工作后在 Init() 方法中注册。问题仍然存在,为什么 ASP.NET 不允许这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2014-02-12
  • 1970-01-01
  • 2021-12-17
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多