Handling application events without Global.asax

My project does not have "global.asax" for various reasons, and I cannot change it (this is a component). In addition, I do not have access to web.config, so httpModule is also not an option.

Is there a way to handle the events of the application as a whole , for example, "BeginRequest"?

I tried this and it did not work, can someone explain why? Looks like an error:

HttpContext.Current.ApplicationInstance.BeginRequest += MyStaticMethod; 
+6
source share
1 answer

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")] 
+9
source

Source: https://habr.com/ru/post/886943/


All Articles