When I call Response.Redirect(someUrl)
I get an HttpException: "Cannot redirect after HTTP headers have been sent".
Why do I get this? And how can I fix this issue?
When I call Response.Redirect(someUrl)
I get an HttpException: "Cannot redirect after HTTP headers have been sent".
Why do I get this? And how can I fix this issue?
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". SinceResponse.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.There are 2 ways to fix this:
Just add a
return
statement after yourResponse.Redirect(someUrl);
( if the method signature is not "void", you will have to return that "type", of course ) as so:Response.Redirect("Login.aspx");
return;
Note the return allows the server to perform the redirect...without it, the server wants to continue executing the rest of your code...
Response.Redirect(someUrl)
the LAST executed statement in the method that is throwing the exception. Replace yourResponse.Redirect(someUrl)
with a string VARIABLE named "someUrl", and set it to the redirect location... as follows://......some code
.....some logic
......more code
// MOVE your Response.Redirect to HERE (the end of the method):
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 callingResponse.Headers.Clear()
before the Redirect to see if that helps.Be sure that you don't use
Response
s' methods likeResponse.Flush();
before your redirecting part.Using
return RedirectPermanent(myUrl)
worked for meThe redirect function probably works by using the 'refresh' http header (and maybe using a 30X code as well). Once the headers have been sent to the client, there is not way for the server to append that redirect command, its too late.