从HttpModule访问Request.Form会中断AutoEventWireUp

本文关键字:中断 AutoEventWireUp Form Request HttpModule 访问 | 更新日期: 2023-09-27 18:29:58

我在一个遗留项目中遇到了一个奇怪的问题,事件的组合导致了意外的行为(无论如何我都是意外的)。我能够在当地重复这个问题;并进行调试以缩小问题范围。我在下面详细介绍了。谢谢注:这是完整的测试复制代码。

开发环境设置

  • Windows 7上的IIS 7.0
  • 集成AppPool.NET 4.5
  • web.config中的HttpModule注册

HttpModule

    public class Logger : IHttpModule
    {
        void IHttpModule.Dispose() {}
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(Context_BeginRequest);
        }
        void Context_BeginRequest(object sender, EventArgs e)
        {
            var _application = (HttpApplication)sender;
            // Comment line below (or change to any other collection) while AutoEventWireUp is true - no problems
            foreach (string key in _application.Request.Form.AllKeys) { }
        }
    }

EventTest.aspx

<%@ Page Language="C#" AutoEventWireup="true" Inherits="EventTest.TestPage" Codebehind="EventTest.aspx.cs" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Test</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label ID="Label1" runat="server"></asp:Label><br />
        <asp:Button id="Button1" runat="server" Text="Submit" OnClick="Button1_Click"></asp:Button>
    </form>
</body>
</html>

EventTest.aspx.cs

using System;
namespace EventTest
{
    public partial class TestPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, System.EventArgs e)
        {
            this.Label1.Text += String.Format("Page_Load fired with PostBack {0}<br />", this.IsPostBack.ToString() );
        }
        override protected void OnInit(EventArgs e)
        {
            // Uncomment this and set AutoEventWireUp to False - no problems
            //this.Load += new EventHandler(Page_Load);
            base.OnInit(e);
        }
        protected void Button1_Click(object sender, System.EventArgs e)
        {
            this.Label1.Text += "Button1_Click Fired<br />";
        }
    }
}

发生了什么

  • 如果AutoEventWireUp为True,并且HttpModule访问Request.Form集合,则不会触发任何事件。

  • 对HttpModule中的Request.Form行进行注释,或者将集合切换到Request.Headers,等等,然后触发所有事件。

  • 如果AutoEventWireUp为False(并且Page_Load是手动注册的),则无论Request.Form访问权限如何,都会触发所有事件。

这不是我需要为项目解决的问题,因为我不使用AutoEventWireUp,但我不明白为什么会发生这种情况。如果有人能对此有所了解;我很感激。

编辑:如果它有帮助,那么从Context_PostAcquireRequestState访问时,这不是问题。我很好奇,因为Form是RO系列,但似乎有一些修改

从HttpModule访问Request.Form会中断AutoEventWireUp

尝试将此函数添加到HttpModule:

public void Init(HttpApplication objApplication)
{
    objApplication.PreRequestHandlerExecute += new EventHandler(this.Application_PreRequestHandlerExecute);
}
private void Application_PreRequestHandlerExecute(object objSender, EventArgs objE)
{
    Page objPage = (Page)(objSender as HttpApplication).Context.Handler; 
    objPage.AutoEventWireup = true;
}