Click here to Skip to main content
15,906,081 members
Articles / Web Development / ASP.NET
Article

Clean page redirect for setting redirect inside logical code

Rate me:
Please Sign up or sign in to vote.
2.67/5 (3 votes)
27 Jun 2005 55.9K   16   11
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.

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.

C#
try
{
  if(obj != null)
  {
    //do some code

    //throws a 'Thread being aborted error' 
    //because a redirect is being done here
    Response.Redirect("Subscribers.aspx"); 
  }
  else
  {
    //some other code
  }
}
catch(Exception ex)
{
  //exception handling code
}

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.

C#
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);
  }

  /// <summary>
  /// Sets the redirect session variable for redirection on page render
  /// </summary>
  /// <param name="path"></param>
  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:

C#
try
{
  if(obj != null)
  {
    //do some code

    //no error throw because the redirect is being done 
    //in the OnPreRender event 
    this.SetPageRedirect(false,"RequestAccess.aspx");
  }
  else
  {
    //some other code
  }
}
catch(Exception ex)
{
  //exception handling code
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Christopher G. Lasater

I am also a published author, please check out my book:
ISBN: 1-59822-031-4
Title: Design Patterns
Author:Christopher G. Lasater
More from my web site
Amazon.com


Comments and Discussions

 
GeneralThere's a better way... Pin
Patrick Heller9-Mar-07 4:20
Patrick Heller9-Mar-07 4:20 
GeneralRe: There's a better way... Pin
Christopher G. Lasater9-Mar-07 4:28
Christopher G. Lasater9-Mar-07 4:28 
GeneralRe: There's a better way... Pin
Patrick Heller9-Mar-07 4:50
Patrick Heller9-Mar-07 4:50 
GeneralRe: There's a better way... Pin
Christopher G. Lasater9-Mar-07 5:05
Christopher G. Lasater9-Mar-07 5:05 
So did you have processing logic after the Response.Redirect? That is usually what causes the problem. If it is fixed in 2.0, well good, but it is generally not a good idea anyway to have too much procesing logic in pages, and even then, to do your thread offshoots (events or redirects in other words) at the end of that page's processing, or as in my example at the re-post of the page. Actually before .net this was a recognized way of dealing with php script errors for the same threading issue, except the logic was not reposted, but forwarded on to a redirect controller. A lot has been said on the subject, but if you understand threading in any system and how it works, you will see the benefit of allowing the page to finish its process. Remember each page run is a thread spun up by IIS using the .NET framework, and the page processes its code by compiling it at run time and then memory caching it for a duration of time. (This is different from @Output Caching or using the System.Caching objects of course).
When a page is redirected or processing is finished and control is returned to the Request thread from the IIS server, that page is then garbage collected. This is what causes the 'Thread Aborted error' because garbage collection to preserve system memory sends a thread abort event to any active or waiting threads. If processing is still going on this gets sent to a kind of abort queue in the threading model, which then will force the cleanup.

Christopher G. Lasater

GeneralWhy?... Pin
Aspera26-Jul-06 13:07
Aspera26-Jul-06 13:07 
GeneralRe: Why?... Pin
Christopher G. Lasater26-Jul-06 17:30
Christopher G. Lasater26-Jul-06 17:30 
GeneralRe: Why?... [modified] Pin
Aspera27-Jul-06 3:21
Aspera27-Jul-06 3:21 
Question'AppConst'? Pin
ParindShah12310-Oct-05 3:11
sussParindShah12310-Oct-05 3:11 
AnswerRe: 'AppConst'? Pin
Matthias Glubrecht1-Dec-05 2:02
Matthias Glubrecht1-Dec-05 2:02 
QuestionIs this an appropriate location for redirecting? Pin
Mark Focas27-Jun-05 13:53
Mark Focas27-Jun-05 13:53 
AnswerRe: Is this an appropriate location for redirecting? Pin
Christopher G. Lasater28-Jun-05 4:42
Christopher G. Lasater28-Jun-05 4:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.