Tuesday, October 15, 2013

Fix "Thread was being aborted" When Redirecting in ASP.NET

If you get "Thread was being aborted" in your logs or email it is because you are using "Response.Redirect" inside a "Try Catch". Here is how you can replicate the problem:

1 2 3 4 5 6 7 8 9 10 11 12 protected void Page_Load(object sender, EventArgs e)
{
try
{
//Some logic here.
Response.Redirect("Default.aspx");
}
catch (Exception ex)
{
//Send error email or log it.
}
}


VB.NET

1 2 3 4 5 6 7 8 Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Try
'Some logic here
Response.Redirect("Default.aspx")
Catch ex As Exception
'Send error email or log it.
End Try
End Sub


You get the "Thread was being aborted" error because you are logging it. This error doesn't stop the user from redirecting nor an actual error page is displayed. To stop getting this error, what you need to do is basically ignore it or take it outside of the "try catch". Here how I ignore it:

1 2 3 4 5 6 7 8 9 10 11 12 13 protected void Page_Load(object sender, EventArgs e)
{
try
{
//Some logic here.
Response.Redirect("Default.aspx");
}
catch (System.Threading.ThreadAbortException ex){ }
catch (Exception ex)
{
//Send error email or log it.
}
}


VB.NET

1 2 3 4 5 6 7 8 9 Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Try
'Some logic here.
Response.Redirect("Default.aspx")
Catch ex As Threading.ThreadAbortException
Catch ex As Exception
'Send error email or log it.
End Try
End Sub


You can also use "Response.Redirect("Default.aspx", false)" but you have to be aware that this overload option will not stop the execution of the code. This means that you have to do it manually like using "Return" right after the redirect. This is not always possible cause you might have nested function calls, etc. Another thing about it is that this allows your page to be accessed via a no redirect hack. In other words, it is up to the client software to redirect or continue displaying your page.

No comments:

Post a Comment