HTTP headers 何时发送?

When the HTTP headers are already sent?

我有这个模块:

public class SecureCookieModule : IHttpModule
{
    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        context.EndRequest += OnEndRequestHandlerExecute;
    }

    private void OnEndRequestHandlerExecute(object sender, EventArgs e)
    {
        if (!AppConfig.MachineAppSettingsBool("setSecureCookiesForSecureConnections"))
        {
            return;
        }

        try
        {
            HttpApplication app = sender as HttpApplication;

            if (app.Request.IsReallySecureConnection())
            {
                foreach (string s in app.Response.Cookies.AllKeys)
                {
                    var cookie = app.Response.Cookies[s];

                    if (cookie.Secure == false)
                    {
                        cookie.Secure = true;
                        app.Response.Cookies.Add(cookie);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogManager.GetLogger("SecureCookieModule").Error("Exception while processing http module. Ex: {0}", ex);
        }
    }
}

从这里我写的在某些情况下响应 headers 已经发送,因此无法修改它们并因此抛出异常。我想念的是在什么情况下会发生这种情况,为什么?为什么在某些情况下会在执行 "OnEndRequestHandlerExecute" 事件之前发送它们,而在其他情况下却不会?导致这种行为的这种情况背后的规则是什么?

提前致谢!

如果没有缓冲响应,并且 headers 已经发送,您不能在结束请求事件期间更改它们,因为它们已经被写回到浏览器的数据流中。

要解决这个问题,您有一个选择:

  1. 开启response buffering。这样您当前的代码将能够修改缓冲区中的 headers(如果您正在提供大型文档,这可能不是一个好主意)。

    Response.BufferOutput = true;
    
  2. 而不是处理 EndRequest,而是处理 PreSendRequestHeaders。此事件保证在 headers 写入响应之前触发。

    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += OnEndRequestHandlerExecute;
    }