Search code examples
asp.nethttpheader

Detect that asp.net http headers already sent


I am adding headers to a page as follows: Page.Response.AddHeader("foo", "bar");

Depending upon previous processing, sometimes this fails with "Server cannot append header after HTTP headers have been sent." I am dealing with this by enclosing Page.Response.AddHeader("foo", "bar"); within a try-catch construct. However, to keep things cleaner and avoid generating an exception is there any way to detect that the headers have already been sent? (btw if I try evaluating Page.Response.Headers then I get the following error: "This operation requires IIS integrated pipeline mode")

Thanks


Solution

  • 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.