asp.net – 在没有Global.asax的情况下处理应用程序范围的事件

由于各种原因,我的项目没有“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")]

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....