在运行时编程注册HttpModules

48

我正在编写一个应用程序,第三方供应商可以编写插件DLL并将它们放入Web应用程序的bin目录中。 我希望这些插件能够在必要时注册自己的HttpModule。

我是否有办法在运行时添加或删除HttpModules到管道中,而不需要在Web.Config中有相应的条目?还是说我必须在添加/删除模块时以编程方式编辑Web.Config? 我知道无论哪种方式都会导致应用程序域重新启动,但我宁愿能够在代码中做到这一点,而不必通过修改web.config来实现相同的效果。

5个回答

54

It has to be done at just the right time in the HttpApplication life cycle which is when the HttpApplication object initializes (multiple times, once for each instance of HttpApplication). The only method where this works correct is HttpApplication Init().

To hook up a module via code you can run code like the following instead of the HttpModule definition in web.config:

  public class Global : System.Web.HttpApplication
  {
     // some modules use explicit interface implementation
     // by declaring this static member as the IHttpModule interface
     // we work around that
     public static IHttpModule Module = new xrnsToashxMappingModule();
     public override void Init()
     {
         base.Init();
         Module.Init(this);
     }
  }

All you do is override the HttpApplication's Init() method and then access the static instance's Init method. Init() of the module hooks up the event and off you go.

通过Rick Strahl的博客


我们正在使用的一个模块在从web.config引用时可以正常工作,但是无法直接实例化(如您的代码所示),因为它被声明为friend。您有任何想法应该从哪个上下文实例化它吗? - Patonza

29

请注意,这是一个旧问题,但是asp.net 4提供了一些新功能,可以在此处提供帮助。

具体而言,ASP.NET 4提供了PreApplicationStartMethod功能,可用于以编程方式添加HttpModules。

我在http://www.nikhilk.net/Config-Free-HttpModule-Registration.aspx上发布了一篇博客文章介绍该功能。

基本思路是创建一个派生的HttpApplication,它提供了在启动时动态添加HttpModules的能力,然后每当应用程序域中创建每个HttpApplication实例时,它就会将它们初始化到管道中。


13
博客已经停止更新...历史链接:http://wayback.archive.org/web/20120719043729/http://www.nikhilk.net/Config-Free-HttpModule-Registration.aspx - felickz

13

Microsoft.Web.Infrastructure.dll中的一个类DynamicModuleUtility有一个方法可以做到这一点。

该dll与WebPages 1.0一起提供。

public static class PreApplicationStartCode
{
    private static bool _startWasCalled;

    public static void Start()
    {
        if (_startWasCalled) return;

        _startWasCalled = true;
        DynamicModuleUtility.RegisterModule(typeof(EventTriggeringHttpModule));
    }
}

3
在新版本的ASP MVC中,您可以使用包管理器添加对WebActivatorX的引用,然后执行以下操作:
using WhateverNameSpacesYouNeed;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourApp.SomeNameSpace.YourClass), "Initialize")]
namespace YourApp.SomeNameSpace
{
  public static void Initialize()
  {
    DynamicModuleUtility.RegisterModule( ... the type that implements IHttpModule ... );
  }
}

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接