12 April 2012

Response.Redirect(url,true) Vs Response.Redirect(url,false)


Response.Redirect(url,true) Vs Response.Redirect(url,false)

To avoid ThreadAbortException while Redirect

You don't need to put the redirect in a try-catch block. Just replace all calls to Response.Redirect(url) with the following lines:

Response.Redirect(url, false);

That will avoid the exception being thrown and gracefully end execution of the thread and event chain.

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:

Post a Comment

Comments Welcome

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...