【问题标题】:ASP.NET HttpModule - guaranteed execution of pre- and post- handler code?ASP.NET HttpModule - 保证执行前处理程序和后处理程序代码?
【发布时间】:2008-11-14 07:27:35
【问题描述】:

基本上,我正在尝试在 ASP.NET HttpModule 中编写以下(伪代码):

*pre-code*
try { handler.ProcessRequest(...) }
catch (Exception) { *error-code* }
finally { *post-code* }

我发现我可以挂接到 HttpModule.PreExecuteHandler 的“预代码”和 .Error 的“错误代码”。但是 PostExecuteHandler 似乎运行不可靠。

BeginRequest 和 EndRequest 运行可靠,但对于我需要编写的代码来说还为时过早,这需要检查选择执行的处理程序。在 BeginRequest 之后才选择处理程序。

有编写这种包装器的最佳实践吗?

谢谢!

【问题讨论】:

    标签: c# asp.net httpmodule


    【解决方案1】:

    除了不调用 Response.End 之外,没有办法做你想做的事(至少在 HttpModule 中)。 This article 很好地解释了它,并提供了 Response.End 的替代方案,以防它是您调用 Server.Transfer 的副作用。

    【讨论】:

    • 谢谢 - 这正是我想要的,不是 Server.Transfer 而是 Request.End()。 PostRequestHandlerExecute 肯定不会执行,但我认为即使在这种情况下 EndRequest 也会被调用?哦,那我去测试一下……
    【解决方案2】:

    将此添加到您的 Global.asax 文件中:

    protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        //
    }
    
    protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
    {
        //
    }
    

    这应该 100% 有效。

    【讨论】:

    • 谢谢,感谢您的回答-但我希望在没有 Global.ASAX 文件的情况下在 HttpModule 中执行此操作。此外,我相信(但尚未在 ASAX 中测试)如果有人在处理程序中执行 Response.End,则 PostRequestHandlerExecute 将永远不会运行。只有 End 事件才会.. (?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多