为什么没有办法从IHttpModule初始化范围中取消绑定HttpApplication事件处理程序

时间:2011-04-29 20:35:06

标签: c# asp.net binding ihttpmodule httpapplication

假设我们希望在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初始化。

1 个答案:

答案 0 :(得分:2)

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

ASP.NET辅助进程创建了多个HttpApplication实例。它们是用于性能目的的,但是对于您的Web应用程序,HttpApplication服务请求肯定会有多个实例。

Here's a pretty good article on the subject