Introduction/Background
There are quite a few posts on the web about this issue. But I haven't found one that addresses all issues with
Response.Redirect
in an ASP.NET web form. We still need the method, and adding false
to the endResponse
flag is only step one of many steps.
If you aren't already aware of this issue. Here's the story:
Response.End()
exists for compatibility with original ASP. Its intent is to halt all execution for that page, preventing subsequent code from executing. Sounds like a great idea right? Problem is it may circumvent some managed code that you needed to execute. As well as causing an expensive ThreadAbortException
to occur.
"Well I don't ever use that so I'm safe", you say? Do you use
Response.Redirect
? Then odds are you call it indirectly.
Response.Redirect(string url, bool endResponse)
So let's cut to the chase. Here's an extension that can be used pretty much anywhere and not require overriding the Page
class.
public static void Redirect(this TemplateControl control, bool ignoreIfInvisible = true)
{
Page page = control.Page;
if (!ignoreIfInvisible || page.Visible)
{
page.Response.Redirect(url, false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
page.Visible = false;
}
}
The important thing to note here is page.Visible = false
. This prevents child controls from rendering as well
as many data bound controls will not fire their events. This not only reduces the chance of an exception or redundant execution,
it flags that a redirect is pending and therefore allows for easy control of code execution. More importantly, this flag helps prevent
unintended subsequent redirects.