Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 473
DEH Avatar asked Sep 21 '10 07:09

DEH


People also ask

How do I check HTTP headers?

If you want to check the HTTP headers or response headers for a particular web page, you can perform the following steps. Open the HTTP Header Checker. Enter any valid domain or IP address to check the response headers, and click on the "Check HTTP Headers" button.

How do you solve Cannot redirect after HTTP headers have been sent?

If you are trying to redirect after the headers have been sent (if, for instance, you are doing an error redirect from a partially-generated page), you can send some client Javascript (location. replace or location. href, etc.) to redirect to whatever URL you want.

What is Httpheaders?

An HTTP header is a field of an HTTP request or response that passes additional context and metadata about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.

How do I view headers in IIS?

You can use failed request tracing in IIS to include status code 200. This would log successful requests too and you can view all request headers in the "request details" > "general request headers" section.


2 Answers

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.

like image 112
Scott Hanselman Avatar answered Sep 21 '22 20:09

Scott Hanselman


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) { ... }
like image 25
ChaseMedallion Avatar answered Sep 24 '22 20:09

ChaseMedallion