【问题标题】:Can I be sure that HttpModules are executed in the order in which they are listed in the HttpApplication.Modules collection?我可以确定 HttpModules 是按照它们在 HttpApplication.Modules 集合中列出的顺序执行的吗?
【发布时间】:2013-02-20 06:34:54
【问题描述】:

我想写一个IHttpModule,必须严格在FormsAuthenticationModule之后执行,否则就没用了。

HttpContext.Current.ApplicationInstance.Modules 属性返回 IHttpModules 的集合。我可以检查我的模块是否在此集合中的 FormsAuthenticationModule 之后。

够了吗?该集合是否按执行顺序列出IHttpModules?

【问题讨论】:

    标签: asp.net .net iis httpmodule


    【解决方案1】:

    回想一下,模块可以订阅不同的管道事件。在任何给定的管道事件中,模块应该按照它们在 Modules 集合中指定的顺序运行。

    作为一个实际示例,想象一个 Modules 集合,其中注册了这三个模块:

    • 模块 A,订阅 EndRequest
    • 模块 B,订阅 BeginRequest 和 EndRequest
    • 模块 C,订阅 AuthenticateRequest

    执行顺序为:

    1. 模块 B,开始请求
    2. 模块 C,AuthenticateRequest
    3. 模块 A,结束请求
    4. 模块 B,结束请求

    由于 FormsAuthenticationModule 订阅了 AuthenticateRequest 事件,请考虑让您自己的模块订阅 PostAuthenticateRequest 事件。这样,您就可以保证如果 FormsAuthenticationModule 逻辑运行,它会在您的逻辑之前运行,而不管它们在 Modules 集合中的注册顺序如何。

    【讨论】:

    • 我明白你的意思,但我不能使用PostAuthenticateRequest,因为我的模块必须撤消 FormsAuthenticationModule 在其EndRequest 处理程序中所做的事情,所以我绝对必须将我的代码放在@987654323 中@我的模块的处理程序。
    • 你能解释一下你到底想做什么吗?如果您试图抑制 FormsAuthenticationModule 的自动“将 401 转换为重定向”行为,请在请求期间的某个时间点设置 HttpResponse.SuppressFormsAuthenticationRedirect = true。
    • 该属性只出现在 ASP.NET 4.5 中。是的,我正试图压制那件事。
    【解决方案2】:

    我会尽力回答的。

    我认为您不应该依赖 HttpContext.Current.ApplicationInstance.Modules 集合,因为您现在需要执行模块的顺序。

    请注意,我没有做任何原型,这只是我的想法。

    dll Microsoft.Web.Infrastructure.dll 有一个动态注册 HTTP 模块的方法

    该 dll 随 WebPages 1.0 提供

    为注册创建帮助类

    public static class RegisterHttpModuleHelper
    {
    
        public static void Start()
        {
    
            DynamicModuleUtility.RegisterModule(typeof(YourCustomModule));
        }
    }
    

    FormsAuthenticationModule 有事件“Authenticate”。

    在此事件的处理方,尝试使用动态注册您的自定义 HttpModule

    public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
    {
        RegisterHttpModuleHelper.Start()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-04
      • 2022-01-18
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多