Wednesday, 22 June 2011

Why you shouldn't use Response.End and how to properly use Response.Redirect

Reposnse.Redirect is provided for compatibility with ASP but people still use its default overload which causes ThreadAbortException under the covers. This exception cannot be caught and has performance impact on your web application - look in "Output" or "Immediate" window in your Visual Studio when you do debugging and see this

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

This is caused by Response.End being internally called by Response.Redirect(someurl).
To avoid it, you may use another overload Response.Redirect(someurl, flase) which doesn't end the response, but it may lead to consequences because the rest of your code behind, after the Redirect, will still be processed.

The solution? Use .End for debugging. Consider using the combination of .Redirect(blah, false) and  HttpContext.Current.ApplicationInstance.CompleteRequest method

Please be warned that the above will end Application, but not Page events chain therefore Page-related events and Postback will still be processed and the page will be rendered, though the client will not see it (need to confirm that)

No comments:

Post a Comment