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;
asax is not required by ASP.NET for a website to run. It is, however, very useful for application-level functionality (like unhandled exception logging). Save this answer.
Global. asax is an optional file which is used to handling higher level application events such as Application_Start, Application_End, Session_Start, Session_End etc.
asax file is used to handle high level application events, such as: Application start. Application error. Session start.
Global. asax contains code which is executed. Web. config contains configuration settings of web application, for example connection string, included libraries, namespaces, users and groups access permissions to virtual directories, etc.
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")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With