Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET Response.Redirect without ThreadAbortException

0.00/5 (No votes)
13 Mar 2013 1  
Response.Redirect(string url) calls Response.End() which then throws a ThreadAbortException. Here's a simple way to solve it.

Introduction/Background

There are quite a few posts on the web about this issue. But I haven't found one that addresses all issues with Response.Redirect in an ASP.NET web form. We still need the method, and adding false to the endResponse flag is only step one of many steps.

If you aren't already aware of this issue.  Here's the story:

Response.End() exists for compatibility with original ASP. Its intent is to halt all execution for that page, preventing subsequent code from executing. Sounds like a great idea right? Problem is it may circumvent some managed code that you needed to execute. As well as causing an expensive ThreadAbortException to occur.

"Well I don't ever use that so I'm safe", you say? Do you use Response.Redirect? Then odds are you call it indirectly.

Response.Redirect(string url, bool endResponse)

So let's cut to the chase. Here's an extension that can be used pretty much anywhere and not require overriding the Page class.

public static void Redirect(this TemplateControl control, bool ignoreIfInvisible = true)
{
  Page page = control.Page;
  if (!ignoreIfInvisible || page.Visible)
  {
    // Sets the page for redirect, but does not abort.
    page.Response.Redirect(url, false);
    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline
    // chain of execution and directly execute the EndRequest event.
    HttpContext.Current.ApplicationInstance.CompleteRequest();

    // By setting this to false, we flag that a redirect is set,
    // and to not render the page contents.
    page.Visible = false;
  }
}

The important thing to note here is page.Visible = false. This prevents child controls from rendering as well as many data bound controls will not fire their events. This not only reduces the chance of an exception or redundant execution, it flags that a redirect is pending and therefore allows for easy control of code execution.  More importantly, this flag helps prevent unintended subsequent redirects.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here