How can I tell when HTTP Headers have been sent in an ASP.NET application?

心不动则不痛 提交于 2019-12-05 11:41:21

问题


Long story short, I have an ASP.NET application I'm trying to debug and at some point, in very particular circumstances, the application will throw exceptions at a Response.Redirect() stating:

"Cannot redirect after HTTP headers have been sent."

Which I more or less get, except that I cannot figure out where the headers were sent.

Is there something to look for in an ASP.NET application that will indicate that the HTTP headers have been sent?

BONUS DIFFICULTY: The ASP.NET app is still in .NET 1.1. The circumstances regarding the delay behind the upgrade are a really sore subject.


回答1:


HttpApplication has an event PreSendRequestHeaders which is called just when headers are writtne. Subscribe to this and log it or add a breakpoint.

Beyond that, HttpResponse has a internal property called HeadersWritten (_headersWritten field in .NET 1.1). Since it's internal you can't access it directly, but you can through reflection. If this is only for internal debugging (i.e., not production code), then it's be fine to use reflection.

Check this method before/after all the page lifecylce events. Once you know which event is writing out the headers, add more HeadersWritten checks to find out where they're getting written. Through progressive narrowing of checks to this property, you'll find it.

New info

HeadersWritten property is public starting from .Net 4.5.2




回答2:


Samuel's reply just solved this problem for me (+1). I can't paste a code sample in a comment, but in the interest of helping others, here's how I used the event he suggested to add a HeadersWritten property to my IHTTPHandler:

protected bool HeadersWritten { get; private set; }

void ApplicationInstance_BeginRequest(object sender, EventArgs e)
{
    HeadersWritten = false;
}

void ApplicationInstance_PreSendRequestHeaders(object sender, EventArgs e)
{
    HeadersWritten = true;
}

public void ProcessRequest(HttpContextBase context)
{
    context.ApplicationInstance.PreSendRequestHeaders += new EventHandler(ApplicationInstance_PreSendRequestHeaders);
    do_some_stuff();
}

In my code that would break if I mess with headers too late, I simply check the HeadersWritten property first:

if (!HeadersWritten)
{
    Context.Response.StatusDescription = get_custom_description(Context.Response.StatusCode);
}


来源:https://stackoverflow.com/questions/2382094/how-can-i-tell-when-http-headers-have-been-sent-in-an-asp-net-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!