Response.Redirect throws “Thread was being aborted”

Response.Redirect causes the browser to redirect to a different URL. It does so by sending a 302 – Object Moved to the browser, requesting it to do another roundtrip to the new page. Here is an example:

protected void Page_Load(object sender, EventArgs e)
{
  try
  {
   if (IsTrue)
      Response.Redirect(“http://www.harigeek.com”, true);
  }
  catch (Exception ex)
  {
    // All exceptions are caught and written
    // to a log file

  }
}

When doing the Response.Redirect, .net will automatically throw an System.Threading.ThreadAbortExcept when the redirect is called.

Cause:

Response.Redirect calls the the Response.End internally which ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

Resolution:

  1. For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
  2. For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
                   
    Response.Redirect ("nextpage.aspx", false);
  3. For Server.Transfer, use the Server.Execute method instead.
  4. Filter the exceptions. Do nothing if the ThreadAbortException occurs:
     protected void Page_Load(object sender, EventArgs e)
    {
     try
      {
       if (IsTrue)
          Response.Redirect(“http://harigeek.com”, true);
      }
      catch (ThreadAbortException ex1)
      {
        // do nothing
      }
      catch (Exception ex2)
      {
       // All remaining exceptions are caught and written
       // to a log file

      }
    }

 
Designed and Maintained by