由于各种原因,我的项目没有“global.asax”,我无法改变它(它是一个组件).此外,我无法访问web.config,因此httpModule也不是一个选项.
有没有办法处理应用程序范围的事件,例如在这种情况下的“BeginRequest”?
我尝试了这个并没有用,有人可以解释原因吗?看起来像一个bug:
HttpContext.Current.ApplicationInstance.BeginRequest += MyStaticMethod;
解决方法
不,这不是一个错误.事件处理程序只能在IHttpModule初始化期间绑定到HttpApplication事件,并且您尝试在Page_Init(我的假设)中的某处添加它.
因此,您需要动态地向所需事件处理程序注册一个http模块.如果你在.NET 4下有一个好消息 – 有PreApplicationStartMethodAttribute属性(引用: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.
所以剩下的事情非常简单:你需要创建自己的http模块,包含你想要的事件处理程序,模块初始化器和属性到AssemblyInfo.cs文件.这是一个模块示例:
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)
{
}
}
要动态注册模块,您可以使用Microsoft.Web.Infrastructure.dll程序集中的DynamicModuleUtility.RegisterModule方法:
public class Initializer
{
public static void Initialize()
{
DynamicModuleUtility.RegisterModule(typeof(MyModule));
}
}
唯一剩下的就是为AssemblyInfo.cs添加必要的属性:
[assembly: PreApplicationStartMethod(typeof(Initializer),"Initialize")]
