Correct use of System.Web.HttpResponse.Redirect

Try very, very hard to avoid using Response.Redirect(url), instead, use Response.Redirect(url, false).  Response.Redirect(url), after writing a 302 redirect response to the response buffers, calls Response.End.  This is very expensive.  The alternative, Response.Redirect(url, false) is fast, but unlike Response.Redirect(url), the lines of code which follow the call to Response.Redirect(url, false) will be executed.  More on this later, but first, let me tell you about the horrors of Response.End.


Response.End is a terrible method.  It was added in ASP.NET 1.0 for compatibility with classic ASP.  In classic ASP, this method terminated script processing, so that the lines of script that followed this call never executed.  How do you simulate that in managed code?  The only way is to abort the thread, which raises a ThreadAbortException and is outrageously expensive.  Normally, that’s exactly what Response.End does in ASP.NET, however, if it is called from within an asynchronous handler/module (a.k.a. an asynchronous pipeline event), it will instead perform a synchronous flush of the response buffers (can you say expensive?) and then complete the request by calling Context.ApplicationInstance.CompleteRequest().  Either way, whether you’re calling it from a synchronous handler/module or an asynchronous handler/module, Response.End is horribly expensive, and you should avoid it.


Ok, so what if you don’t want the lines of code to execute after you redirect?  Well, one way to accomplish this is to call HttpApplication.CompleteRequest(), which is accessible from the HttpContext. e.g., call calling Context.ApplicationInstance.CompleteRequest().  It’s not the same as aborting the thread, which truly does prevent all subsequent lines of code form running.  The lines of code that follow the call to CompleteRequest() will execute, but as soon as the current page or module that calls this completes, the pipeline will jump ahead to the EndRequest event, thereby short circuiting the pipeline.  This is usually all you need.


So to summarize…






Response.Redirect(url, false);



But before I put my pen away, there’s one more common practice I’ve seen that people should be aware of .  In classic mode, calling Response.Redirect(url) from Application_Error without calling Server.ClearError is doubly expensive.  It causes three exceptions to be thrown, and then either raises a ThreadAbortException or does a synchronous flush and completes the response.  And in integrated mode, calling Response.Redirect(url) from Application_Error without calling Server.ClearError does not even work.  Instead, you should use the following code, which performs well in both classic mode and integrated mode.  If you’re going to redirect from Application_Error, you should do it the following way:



void Application_Error(object sender, EventArgs e)



        Response.Redirect(url, false);




The behavior difference between classic and integrated mode with respect to calling Redirect from Application_Error without calling Server.ClearError is just due to the different environments.  You might notice that with a default 3.5 install, if you remove the ASP.NET ScriptModule from the IIS <modules> section, you’re suddenly able to call Redirect from Application_Error without calling Server.ClearError.  ScriptModule registers a PreSendRequestHeaders handler.  In integrated mode, the PreSendRequestHeaders event is implemented differently.  As a result, in integrated mode, the exception will be rendered if you try to redirect without clearing the error from Application_Error.  I’ve attached a sample that demonstrates the difference between the two pipelines.  This sample will demonstrate the difference regardless of whether or not ScriptModule is installed.  Just request default.aspx.  Then change the value of demonstratePipelineDifference in global.asax, and request default.aspx again.  Do this in both classic mode and integrated mode, and observe the behavior.




Comments (11)

  1. Vijay says:

    Thanks for writing the post

    What if add 2 more lines along with code shown above.

               HttpContext.Current.Response.Redirect("login.aspx", false);




  2. Jonathan says:

    Isn't executing the rest of the code also "expensive"?

  3. Jonathan, yes, but it depends on what the rest of the code is.  The ASP.NET framework code itself is definitely not as expensive as aborting the thread, but the user code could be more expensive than aborting the thread.  The best solution is to avoid aborting the thread and to execute only a small amount of code.  Just use your best judgment.  

  4. Vijay, Redirect calls Clear, so the call to Clear that you added is redundant.

  5. David says:

    Redirection within loggedin  event handler ("LoginButton_Click") does not work:

    protected void LoginButton_Click(object sender, EventArgs e)





    Though it works with other event handlers such as button click.

  6. Neil says:

    Thanks for this. Now my http handler doesn't throw exceptions when redirecting.

  7. Anon says:

    But how then do you have your code send a file to the client (that's doing a download) and be sure of avoiding any corruption of the downloaded file? CompleteRequest doesn't stop everything so won't prevent other stuff from appending things to the download and potentially corrupting it.

    I don't see much official "best practice" documentation on this.

  8. xiboliyalangwolf says:

    It's a good paper to introduce Response.redirect() for those who using it first time.Thanks

  9. LonelyPixel says:

    Be aware that the Page_PreRender method is still called when you don't end the request! I just discovered that this method does a lot of work in my (old) application and resets some session values that were meant to not be set anymore after redirecting. So I need to prevent the PreRender event from being executed after this.

  10. LonelyPixel says:

    Okay, now that I've changed all my code, I'm going to revert that change and continue to use Redirect(…, true). The problem is that ALL page events (just not the application events, which don't do much anyway) continue to execute if the request is not terminated. That's a major issue because the rest of the page may not function properly after I've decided to redirect somewhere else. And it may take a long time which can completely be avoided. Here's another comment on this:…/proper-way-to-skip-page-execution-after-response-redirecttoroute

  11. Jacob says:

    Thank you Thomas, this fixed my Chrome error "net::ERR_INCOMPLETE_CHUNKED_ENCODING" after calling Response.End() or Response.Close().