Wednesday, August 03, 2011

Cons of Response.Redirect(url, false)

Took me a while to find this redirect issue. Glad I can across this blog from Jon B. Gallant.

Quote from Jon B. Gallant http://blogs.msdn.com/b/jongallant/archive/2006/06/20/640484.aspx

The second parameter overload of Response.Redirect is nice because it doesn't call Response.End, which is responsible for throwing the ThreadAbortException. BUT...

The drawback to using this is that the page will continue to process on the server and be sent to the client. If you are doing a redirect in Page_Init (or like) and call Response.Redirect(url, false) the page will only redirect once the current page is done executing. This means that any server side processing you are performing on that page WILL get executed. In most cases, I will take the exception perf hit over the rendering perf hit, esp since the page won't be rendered anyway and that page could potentially have a ton of data. Using Fiddler I was also able monitor my http traffic and see that when using this redirect method the page is actually being sent to the client as well.

I don't usually do redirects in try/catch blocks, but if you do the ThreadAbortException will be handled by your catch and potentially cause a transaction Abort (depending on what you are doing of course). If you do put the redirect in the try block, then you'll need to explicitly catch the ThreadAbortException or create a wrapper method that does that for you.

Something like this would work.

///


/// Provides functionality for redirecting http requests.
///

public static class RedirectUtility
{
///
/// Redirects to the given url and swallows ThreadAbortException that is raised by the Redirect call.
///

/// The url to redirect to.
public static void Redirect(string url)
{
try
{
HttpContext.Current.Response.Redirect(url, true);
}
catch (ThreadAbortException)
{
}
}
}

No comments: