Ben Hoffman Ben Hoffman - 1 month ago 24
ASP.NET (C#) Question

Why Response.Redirect causes System.Threading.ThreadAbortException?

When I use Response.Redirect(...) to redirect my form to a new page I get the error:


A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll

An exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll but was not handled in user code


My understanding of this is that the error is being caused by the webserver aborting the remainder of the page the response.redirect was called on.

I know I can add a second parameter to
Response.Redirect
that is called endResponse. If I set endResponse to True I still get the error but if I set it to False then I do not. I am pretty sure though that that means the webserver is running the rest of the page I redirected away from. Which would seem to be inefficient to say the least. Is there a better way to do this? Something other than
Response.Redirect
or is there a way to force the old page to stop loading where I will not get a
ThreadAbortException
?

Answer

The correct pattern is to call the Redirect overload with endResponse=false and make a call to tell the IIS pipeline that it should advance directly to the EndRequest stage once you return control:

Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();

This blog post from Thomas Marquardt provides additional details, including how to handle the special case of redirecting inside an Application_Error handler.

Comments