4

假设我们只想在 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);
    }
}

将抛出以下异常:

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

4

1 回答 1

2

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

多个HttpApplication实例由 ASP.NET 工作进程创建。HttpApplication它们是出于性能目的而汇集的,但对于您的 Web 应用程序,服务请求肯定可以有多个实例。

这是一篇关于这个主题的非常好的文章

于 2011-04-29T21:19:29.033 回答