Reputation: 781
I have this module:
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);
}
}
}
From this what I wrote in some cases the response headers are already sent, so they cannot be modified and exception is thrown because of this. What I miss is in which cases this happens and why? Why in some cases before executing the "OnEndRequestHandlerExecute" event they are sent and in other cases they are not? What is the rule behind this cases resulting in this behavior?
Thanks in advance!
Upvotes: 1
Views: 1569
Reputation: 52210
If the response is not buffered, and the headers are already sent, you can't change them during the end request event, because they have already been written back to the data stream to the browser.
To deal with this, you have a choice:
Turn response buffering on. That way your current code will be able to modify the headers in the buffer (This might not be a great idea if you are serving large documents).
Response.BufferOutput = true;
Instead of handling EndRequest
, handle PreSendRequestHeaders instead. This event is guaranteed to fire before the headers are written to the response.
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += OnEndRequestHandlerExecute;
}
Upvotes: 2