[asp.net] 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?

This question is related to asp.net http-headers response.redirect httpexception

The answer is


Be sure that you don't use Responses' methods like Response.Flush(); before your redirecting part.


There are 2 ways to fix this:

  1. Just add a return statement after your Response.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...

  1. Make your Response.Redirect(someUrl) the LAST executed statement in the method that is throwing the exception. Replace your Response.Redirect(someUrl) with a string VARIABLE named "someUrl", and set it to the redirect location... as follows:

//......some code

string someUrl = String.Empty

.....some logic

if (x=y)
{
    // comment (original location of Response.Redirect("Login.aspx");)
    someUrl = "Login.aspx";
}

......more code

// MOVE your Response.Redirect to HERE (the end of the method):

Response.Redirect(someUrl);
return; 

You can also use below mentioned code

Response.Write("<script type='text/javascript'>"); Response.Write("window.location = '" + redirect url + "'</script>");Response.Flush();

My Issue got resolved by adding the Exception Handler to handle "Cannot redirect after HTTP headers have been sent". this Error as shown below code

catch (System.Threading.ThreadAbortException)
        {
            // To Handle HTTP Exception "Cannot redirect after HTTP headers have been sent".
        }
        catch (Exception e)
        {//Here you can put your context.response.redirect("page.aspx");}

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.


If you get Cannot redirect after HTTP headers have been sent then try this below code.

HttpContext.Current.Server.ClearError();
// Response.Headers.Clear();
HttpContext.Current.Response.Redirect("/Home/Login",false);

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.


Error Cannot redirect after HTTP headers have been sent.

System.Web.HttpException (0x80004005): Cannot redirect after HTTP headers have been sent.

Suggestion

If we use asp.net mvc and working on same controller and redirect to different Action then you do not need to write..
Response.Redirect("ActionName","ControllerName");
its better to use only
return RedirectToAction("ActionName");
or
return View("ViewName");


Just check if you have set the buffering option to false (by default its true). For response.redirect to work,

  1. Buffering should be true,
  2. you should not have sent more data using response.write which exceeds the default buffer size (in which case it will flush itself causing the headers to be sent) therefore disallowing you to redirect.

The 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.


There is one simple answer for this: You have been output something else, like text, or anything related to output from your page before you send your header. This affect why you get that error.

Just check your code for posible output or you can put the header on top of your method so it will be send first.


I solved the problem using: Response.RedirectToRoute("CultureEnabled", RouteData.Values); instead of Response.Redirect.


Using return RedirectPermanent(myUrl) worked for me


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. Of course, that depends on what HTML has already been sent down.


Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to http-headers

Set cookies for cross origin requests Adding a HTTP header to the Angular HttpClient doesn't send the header, why? Passing headers with axios POST request What is HTTP "Host" header? CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Using Axios GET with Authorization Header in React-Native App Axios get access to response header fields Custom header to HttpClient request Send multipart/form-data files with angular using $http Best HTTP Authorization header type for JWT

Examples related to response.redirect

Redirecting new tab on button click.(Response.Redirect) in asp.net C# go to link on button click - jquery Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()? Response.Redirect to new window Response.Redirect with POST instead of Get?

Examples related to httpexception

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