Posted on November 30, 2010 by briancaos http://briancaos.wordpress.com/2010/11/30/response-redirect-throws-an-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 (somethingIsTrue)
Response.Redirect("http://www.pentia.dk", true);
}
catch (Exception ex)
{
// All exceptions are caught and written
// to a log file
}
}
But here is something I didn’t know. When doing the Response.Redirect, .net will automatically throw an System.Threading.ThreadAbortException when the redirect is called. Apparently this is by design (although I’m nor sure I agree with the design). The code above will write a log line for each time the Response.Redirect is called. This will flood my log file.
-
Set the EndResponse (the 2nd parameter) to false. The thread is aborted when the response is ended, so if you do not end the response, no abortion is done (this is untested, but according to several blogs valid).
-
Move the Response.Redirect outside the try/catch block.
-
Filter the exceptions. Do nothing if the ThreadAbortException occurs:
protected void Page_Load(object sender, EventArgs e) { try { if (somethingIsTrue) Response.Redirect("http://www.pentia.dk", true); } catch (ThreadAbortException ex1) { // do nothing } catch (Exception ex2) { // All remaining exceptions are caught and written // to a log file } }
-
Do not use Response.Redirect. Instead, modify the response headers (this is the rather stupid solution, but I have added it to show that you can redirect without using Response.Redirect):
Response.Clear(); Response.Status = "302 Object Moved"; Response.RedirectLocation = "http://www.pentia.dk"; Response.End();