Today in one of my requirement, I had to redirect to a URL from my current webpage.
As we are totally aware of the code used for this :
But I came across a blog which discussed the cons of using this code. When I studied this further in detail; I thought it would be great to discuss this in bit detail.
The other Overload of this Redirect Method is:
Redirect(String URL , bool endResponse) Where: URL -> The location of the Target page. endResponse -> Indicates whether execution of the current page should terminate.
- 1> Response.Redirect(“URL”) / Response.Redirect(“URL”,True)
This is the default behavior of a redirect. The client will send the redirect for the URL/New Page and the Current page will immediately stop processing, as a thread abort will occur.
E.g: Response.Redirect(“http://www.google.com “);
Mostly while using this, ThreadAbortException is thrown. This happens because the system aborts processing of the current webpage thread after it sends the redirect to the response stream. Means the line right after the call to Redirect does not execute.
Internally, Response.Redirect(URL) makes a call to Response.End() and that call Thread.Abort() which forces the stack to end the thread.
Many suggest using TRY and CATCH block, but using the next Overload method is the best option , to redirect without calling Response.End()
- 2> Response.Redirect(“URL”,False)
Here the client will send the redirect for the URL/New Page, but the Current page will be allowed to continue processing.
E.g: Response.Redirect(“http://www.google.co.in “,False);
This will probably save you from the ThreadAbortException, but what if you don’t want the lines of code to execute after you redirect.
Well, one way to accomplish that is to call CompleteRequest() right after calling Response.Redirect(URL,False). This is a method of the ApplicationInstance object, which we can get from the current context. i.e.
Its not same as aborting the thread, which truly does prevent all subsequent lines of code from running. The line of code that follows the call to CompleteRequest() will execute, but as soon as the current page or module that calls this completes, the pipeline will jump ahead to the EndRequest Event.
So, Its always a good practice to use:
A much detailed explanation is provided here.
Hope this was helpful as it will avoid falling into the Exception most of the time.