使用 Microsoft.Web.Infrastructure 程序集,我们可以在预应用程序启动阶段注册模块,如下所示:
DynamicModuleUtility.RegisterModule(typeof(MyHttpModule));
是否可以在代码中的 ASP.NET Web 表单中注册自定义 PageHandlerFactory
,而不是像上面的模块示例那样?
我目前通过这样的代码连接它,但我发现它太冗长(并且它使得创建快速启动 NuGet 包变得更加困难,因为我必须更改 web.config):
<?xml version="1.0"?>
<configuration>
<system.webServer>
<handlers>
<add name="CustomFactory" verb="*" path="*.aspx"
type="Shared.CustomPageHandlerFactory, Shared"/>
</handlers>
</system.webServer>
</configuration>
最佳答案
据我所知,没有办法在代码中做到这一点。然而,在我的特殊情况下,解决方案实际上是注册一个 HTTP 模块。
HTTP 模块可以在初始化时 Hook 到 HttpApplication.PreRequestHandlerExecute在页面处理程序工厂创建页面之后,但在 ASP.NET 开始执行该页面(和其他处理程序)之前执行的事件。
这是一个这样的 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.
}
}
}
关于c# - 通过代码注册一个自定义的 PageHandlerFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15522541/