ASP.NET classics: using Response.Redirect and avoiding the “thread aborted” exception
Posted: (EET/GMT+2)
In interactive ASP.NET applications, there's often the need to redirect the user from one page to another, for example after form submission. The Response object contains the Redirect method for this purpose, which causes the web application to return a HTTP 302 redirect response.
However, there's a particular issue with this method which can bite you, if you are not careful: calling the Response.Redirect method without extra parameters (just the destination URL), the processing will immediately end, and the thread processing your request will effectively stop.
While this can be useful in simple situations, in more complex logic, this can be an issue because all extra code (such as try…finally blocks) will suddenly start to cause ThreadAbortedExceptions with the message "Thread was being aborted".
To solve this, it is usually best to append one extra Boolean parameter to the method call, specifying false. This means that the thread is not stopped, but instead continues processing normally. For example, if you have a Entity Framework (or other database access) model dispose command after a Response.Redirect call, your code will work as you might expect.
There's also a Microsoft knowledge base article about this particular issue.
Hope this helps!