在没有Global.asax的情况下处理应用程序范围的事件 [英] Handling application-wide events without Global.asax

查看:47
本文介绍了在没有Global.asax的情况下处理应用程序范围的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于各种原因,我的项目没有"global.asax",而且我无法更改它(它是一个组件).另外,我无权访问web.config,因此也不可以使用httpModule.

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.

是否可以处理应用程序范围内的事件,例如本例中的"BeginRequest"?

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;

推荐答案

不,这不是bug.事件处理程序只能在 IHttpModule 初始化期间绑定到 HttpApplication 事件,并且您试图将其添加到 Page_Init 中的某个位置(我的假设).

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).

因此,您需要动态地向所需的事件处理程序注册一个http模块.如果您使用的是.NET 4,那么对您来说是个好消息-有 PreApplicationStartMethodAttribute 属性(参考:

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):

此新属性使您可以早期在ASP.NET中运行代码应用程序启动时的管道.我的意思是早一点,甚至更早 Application_Start .

剩下的事情非常简单:您需要使用所需的事件处理程序,模块初始化程序和 AssemblyInfo.cs 文件的属性来创建自己的http模块.这是一个模块示例:

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));
    }
}

剩下的唯一事情就是将必要的属性添加到您的 AssemblyInfo.cs :

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

[assembly: PreApplicationStartMethod(typeof(Initializer), "Initialize")]

这篇关于在没有Global.asax的情况下处理应用程序范围的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆