使用Microsoft.Web.Infrastructure程序集,我们可以在预应用程序启动阶段注册模块,如下所示:
DynamicModuleUtility.RegisterModule(typeof(MyHttpModule));
是否可以在代码中注册ASP.NET Web表单中的自定义PageHandlerFactory
,就像上面的模块一样?
我目前通过这样的代码连接它,但是我觉得它太冗长了(因为我必须改变web.config,所以创建一个快速启动的NuGet包更加困难):
<?xml version="1.0"?>
<configuration>
<system.webServer>
<handlers>
<add name="CustomFactory" verb="*" path="*.aspx"
type="Shared.CustomPageHandlerFactory, Shared"/>
</handlers>
</system.webServer>
</configuration>
答案 0 :(得分:1)
据我所知,在代码中无法做到这一点。然而,在我的特殊情况下,解决方案实际上是注册HTTP模块。
HTTP模块可以在初始化时挂钩到页面处理程序工厂创建页面之后但在ASP.NET开始执行该页面(以及其他处理程序)之前执行的HttpApplication.PreRequestHandlerExecute事件。
以下是此类HTTP模块的示例:
public class MyHttpModule : IHttpModule
{
void IHttpModule.Dispose() {
}
void IHttpModule.Init(HttpApplication context) {
context.PreRequestHandlerExecute +=
this.PreRequestHandlerExecute;
}
private void PreRequestHandlerExecute(object s, EventArgs e) {
IHttpHandler handler =
this.application.Context.CurrentHandler;
// CurrentHandler can be null
if (handler != null) {
// TODO: Initialization here.
}
}
}