"Cannot redirect after HTTP headers have been sent."

I am trying to redirect from an ASP.NET MVC Controller Action to a static domain address. But I get the followinng exception "Cannot redirect after HTTP headers have been sent."

Any suggestions?

public ActionResult DataAdmin()
            return Redirect("http://www.google.com");

Open in new window

newbiewebSr. Software EngineerAsked:
Who is Participating?
Randy DownsOWNERCommented:
Try this - http://stackoverflow.com/questions/159523/why-do-i-get-cannot-redirect-after-http-headers-have-been-sent-when-i-call-resp

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");
Roman GhermanSenior Software EngineerCommented:

It looks like your headers have been set already in another place.

Try calling Response.Headers.Clear() before the Redirect to see if that helps

Find me on: www.extremedev.blogspot.com
it means that you have already written something to the output
newbiewebSr. Software EngineerAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.