Samuel Meacham Samuel Meacham - 1 month ago 11
ASP.NET (C#) Question

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 an HttpException: "Cannot redirect after HTTP headers have been sent".

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

Answer

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");
Comments