Monday, April 29, 2013

difference between Response.Redirect(url) and Response.Redirect(url, false)

Avoid using Response.Redirect(url), instead, use Response.Redirect(url, false):

I have faced the issue, In our project generalize redirect code was written and it is called from other places. We just pass the redirect url to that generalize function. At few places there was a code after redirect function call. we don't wanted that code to be executed if redirect is happened and this call to redirect is based on particular condition. I started to check why it is happening then i came to know about the actual working of response.redirect()

 Response.Redirect(url): 

        After writing a 302 redirect response to the response buffers, calls Response.End. This is very expensive. 

Response.Redirect(url, false): 

   It is fast, but unlike Response.Redirect(url), the lines of code which follow the call to Response.Redirect(url, false) will be executed.

Horrors of Response.End:
     what if you don't want the lines of code to execute after you redirect? Well, one way to accomplish this is to call HttpApplication.CompleteRequest(), which is accessible from the HttpContext. e.g., call calling Context.ApplicationInstance.CompleteRequest(). It's not the same as aborting the thread, which truly does prevent all subsequent lines of code form running. The lines of code that follow 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.


BAD:
Response.Redirect(url);
GOOD:
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
GOOD:
void Application_Error(object sender, EventArgs e)
{
Server.ClearError();
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
}




I hope this helps to understand why to use Response.Redirect(url, false) over Response.Redirect(url).

Happy Coding!!

No comments:

Post a Comment