Response.Redirect not ending execution

Chad picture Chad · Dec 16, 2008 · Viewed 25.3k times · Source

I have Default.aspx page, which inherits from BasePage.cs, which inherits from System.Web.UI.Page. BasePage is where I do some common things every page must do upon loading.

In BasePage, lets say I'm checking for X. If X=1, then I will redirect to my "Discontinued.aspx" page immediately and stop execution of BasePage. If I find X=1, I say:

HttpContext.Current.Response.Redirect("Discontinued.aspx", true);

I want the redirect to stop execution of BasePage and immediately jump out - hence the "true" in the above statement - which should stop execution of the current page as I understand. The problem is, it doesn't. I'm expecting the redirect to throw the "thread abort exception".

When I run in debug mode, it contines stepping through as though it didn't just redirect and leave.

But the redirect was still started as well - once I get done stepping through the rest of BasePage, the "Discontinued" page then begins to load as a result of the redirect.

Is there a reason my Redirect will not kill execution of BasePage?

Answer

Shawn picture Shawn · Dec 16, 2008

The second parameter for Response.Redirect is endResponse, however the tooltip says 'Indicates whether execution of the current page should terminate'. This is misleading, because the execution of the page does not actually terminate when the variable is true. It will finish running any code. However what does happen differently, is the Render events are canceled, and the Response is immediately flushed with the object moved header.

You need to manually exit out of any methods, Response.Redirect / Response.End will not do that for you. Futhermore, if you need a conditional to see if the Page has been redirected, check out Response.IsRequestBeingRedirected.