Freigeben über


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

 

BAD:

Response.Redirect(url);

GOOD:

Response.Redirect(url, false);

Context.ApplicationInstance.CompleteRequest() ;

      

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:

 

GOOD:

void Application_Error(object sender, EventArgs e)

    {

        Server.ClearError() ;

        Response.Redirect(url, false);

        Context.ApplicationInstance.CompleteRequest() ;

    }

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.

Thanks,

Thomas

sample.zip

Comments

  • Anonymous
    November 14, 2011
    Thanks for writing the post What if add 2 more lines along with code shown above.            HttpContext.Current.Response.Redirect("login.aspx", false);            HttpContext.Current.Response.Clear();            HttpContext.Current.ApplicationInstance.CompleteRequest();            return;

  • Anonymous
    April 13, 2012
    Isn't executing the rest of the code also "expensive"?

  • Anonymous
    April 20, 2012
    The comment has been removed

  • Anonymous
    April 20, 2012
    Vijay, Redirect calls Clear, so the call to Clear that you added is redundant.

  • Anonymous
    July 14, 2012
    Redirection within loggedin  event handler ("LoginButton_Click") does not work: protected void LoginButton_Click(object sender, EventArgs e)    {        Response.Redirect("~/About.aspx",false);        Context.ApplicationInstance.CompleteRequest();    } Though it works with other event handlers such as button click.

  • Anonymous
    October 10, 2012
    Thanks for this. Now my http handler doesn't throw exceptions when redirecting.

  • Anonymous
    February 11, 2014
    But how then do you have your asp.net 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.

  • Anonymous
    April 16, 2014
    It's a good paper to introduce Response.redirect() for those who using it first time.Thanks

  • Anonymous
    June 05, 2014
    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.

  • Anonymous
    June 05, 2014
    The comment has been removed

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