Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

When I call Response.Redirect(someUrl) I get the following HttpException:

Cannot redirect after HTTP headers have been sent.

Why do I get this? And how can I fix this issue?

like image 566
Samuel Meacham Avatar asked Oct 01 '08 20:10

Samuel Meacham


3 Answers

According to the MSDN documentation for Response.Redirect(string url), it will throw an HttpException when "a redirection is attempted after the HTTP headers have been sent". Since Response.Redirect(string url) uses the Http "Location" response header (http://en.wikipedia.org/wiki/HTTP_headers#Responses), calling it will cause the headers to be sent to the client. This means that if you call it a second time, or if you call it after you've caused the headers to be sent in some other way, you'll get the HttpException.

One way to guard against calling Response.Redirect() multiple times is to check the Response.IsRequestBeingRedirected property (bool) before calling it.

// Causes headers to be sent to the client (Http "Location" response header)
Response.Redirect("http://www.stackoverflow.com");
if (!Response.IsRequestBeingRedirected)
    // Will not be called
    Response.Redirect("http://www.google.com");
like image 147
Samuel Meacham Avatar answered Nov 07 '22 12:11

Samuel Meacham


Once you send any content at all to the client, the HTTP headers have already been sent. A Response.Redirect() call works by sending special information in the headers that make the browser ask for a different URL.

Since the headers were already sent, asp.net can't do what you want (modify the headers)

You can get around this by a) either doing the Redirect before you do anything else, or b) try using Response.Buffer = true before you do anything else, to make sure that no output is sent to the client until the whole page is done executing.

like image 17
Philip Rieck Avatar answered Nov 07 '22 12:11

Philip Rieck


A Redirect can only happen if the first line in an HTTP message is "HTTP/1.x 3xx Redirect Reason".

If you already called Response.Write() or set some headers, it'll be too late for a redirect. You can try calling Response.Headers.Clear() before the Redirect to see if that helps.

like image 8
Mark Cidade Avatar answered Nov 07 '22 10:11

Mark Cidade