Let's say we want to execute some action only once or a couple of times after web application has started and during a web request.
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);
}
}
The following exception will be thrown:
Event handlers can only be bound to HttpApplication events during IHttpModule initialization.