假设我们只想在 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 事件。