No, this is not a mistake. Event handlers can only be attached to HttpApplication events during the initialization of IHttpModule , and you are trying to add it somewhere in Page_Init (my guess).
So, you need to dynamically register the http module with the required event handlers. If you use .NET 4, there is good news for you - there is the PreApplicationStartMethodAttribute attribute (link: Three hidden Gems extensibilities in ASP.NET 4 ):
This new attribute allows you to run code at the beginning of ASP.NET as the application starts. I mean the way before, even before Application_Start .
So, the rest is pretty simple: you need to create your own http module with the event handlers you want, the module initializer and the attribute for your AssemblyInfo.cs file. Here is an example module:
public class MyModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } public void Dispose() { } void context_BeginRequest(object sender, EventArgs e) { } }
To dynamically register a module, you can use the DynamicModuleUtility.RegisterModule method from the Microsoft.Web.Infrastructure.dll assembly:
public class Initializer { public static void Initialize() { DynamicModuleUtility.RegisterModule(typeof(MyModule)); } }
it remains only to add the necessary attribute to your AssemblyInfo.cs :
[assembly: PreApplicationStartMethod(typeof(Initializer), "Initialize")]
source share