Search This Blog

Saturday, 22 December 2012

Response.Redirect throws an Exception “Thread was being aborted”

Usually when I involve in SharePoint development, I log the exception in a SharePoint list to refer the exception details. Then I identified “Thread was being aborted” exception while using Response.Redirect() in my WebPart. So I refer the below link to handle this, also I write the solution to handle this issue here.


Post from 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("URL");
}
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.

There are 4 solutions.
1) 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).

2) Move the Response.Redirect outside the try/catch block.

3) Filter the exceptions. Do nothing if the ThreadAbortException occurs:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (somethingIsTrue)
Response.Redirect("URL");
}
catch (ThreadAbortException ex1)
{
   // do nothing
}
catch (Exception ex)
{
// All exceptions are caught and written
// to a log file
}
} 

4) 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 = "URL";
Response.End();

No comments:

Post a Comment