Introduction
This article will detail how you can use the OnPreRender
event to redirect a page from inside a logical set of code without getting the 'Thread was being aborted' error.
We start with the code in its error producing state. We are trying to redirect a page before all the code in the page is finished running, causing a thread abort on the page.
try
{
if(obj != null)
{
Response.Redirect("Subscribers.aspx");
}
else
{
}
}
catch(Exception ex)
{
}
So to fix this we need to build a base page to inherit from and use the OnPreRender
event to actually perform redirects before the page reloads completely, keeping threads from previous server processing from being aborted. We also create a handy page method SetPageRedirect
that adds the URL to be redirected to to the session for access on the OnPreRender
event.
public class GlobalPage
{
protected override void OnPreRender(EventArgs e)
{
if(Session[AppConst.PAGE_REDIRECT]!=null)
{
string redirectPage = Session["PAGE_REDIRECT"].ToString();
Session["PAGE_REDIRECT"] = null;
Response.Redirect(redirectPage);
}
base.OnPreRender (e);
}
public void SetPageRedirect(bool addRootPath, string path)
{
if(!path.StartsWith("/") && addRootPath)
path = RootPath + "/" + path;
else if (addRootPath)
path = RootPath + path;
Session[AppConst.PAGE_REDIRECT] = path;
}
So now we can inherit from this new page and use the functions to avoid getting any error:
try
{
if(obj != null)
{
this.SetPageRedirect(false,"RequestAccess.aspx");
}
else
{
}
}
catch(Exception ex)
{
}