7

My project has no "global.asax" for various reasons and I can't change that (it's a component). Also, I have no access to web.config, so an httpModule is also not an option.

Is there a way to handle application-wide events, like "BeginRequest" in this case?

I tried this and it didn't work, can someone explain why? Seems like a bug:

HttpContext.Current.ApplicationInstance.BeginRequest += MyStaticMethod;
Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149

1 Answers1

11

No, this is not a bug. Event handlers can only be bound to HttpApplication events during IHttpModule initialization and you're trying to add it somewhere in the Page_Init(my assumption).

So you need to register a http module with desired event handlers dynamically. If you're under .NET 4 there is a good news for you - there is PreApplicationStartMethodAttribute attribute (a reference: Three Hidden Extensibility Gems in ASP.NET 4):

This new attribute allows you to have code run way early in the ASP.NET pipeline as an application starts up. I mean way early, even before Application_Start.

So the things left are pretty simple: you need to create your own http module with event handlers you want, module initializer and attribute to your AssemblyInfo.cs file . Here is a module example:

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 register module dynamically you could use DynamicModuleUtility.RegisterModule method from the Microsoft.Web.Infrastructure.dll assembly:

public class Initializer
{
    public static void Initialize()
    {
        DynamicModuleUtility.RegisterModule(typeof(MyModule));
    }
}

the only thing left is to add the necessary attribute to your AssemblyInfo.cs:

[assembly: PreApplicationStartMethod(typeof(Initializer), "Initialize")]
Oleks
  • 31,955
  • 11
  • 77
  • 132
  • 1
    Nice! I was having a problem where a custom HTTP error handler (loaded via web.config) was interfering with IIS warm-up processes. Loading the DLL seemed to be blocking the warm-up process from kicking off immediately and as a result I didn't see the remapManagedRequestsTo file load until the app had loaded, negating it's usefulness. Using this method to load the module seems to address the issue and the warm-up process is kicking off immediately. – BrianS Nov 28 '19 at 02:23
  • It appears here in 2021 Microsoft has marked this method of registration as obsolete, and the new way is HttpApplication.RegisterModule() https://stackoverflow.com/a/54097973/176877 – Chris Moschini Dec 29 '21 at 23:02