Detect that asp.net http headers already sent

You can use an HttpModule to register for the PreSendRequestHeaders event. When it gets called, write a value to HttpContext.Current.Items indicating that the headers are being sent – and then everywhere else in your code you check the value in HttpContext.Current.Items to see if its been sent yet.


UPDATE: the HeadersWritten property is now available on the HttpResponse object.

Unfortunately, whilst the HttpResponse object has a property called HeadersWritten, and a backing field called _headersWritten, neither of these are accessible from outside of the System.Web assembly - unless you use Reflection. I'm not clear what you think you'll be able to obtain from the Headers collection, it may or may not exist, independently of whether the headers have been sent yet.

If you want to use Reflection, it may have it's own performance penalties, and it will require your application to run in full trust.

All of the publicly accessible methods on HttpResponse that involve the _headersWritten field seem to use it to throw an exception.


As of .NET 4.5.2, you can do this using the now-public HeadersWritten property of HttpResponse (see the msdn docs):

if (HttpContext.Current.Response.HeadersWritten) { ... }