THEMike
THEMike

Reputation: 1741

Response.Redirect() ThreadAbortException Bubbling Too High Intermittently

I understand (now) that Response.Redirect() and Response.End() throw a ThreadAbortException as an expensive way of killing the current processing thread to emulate the behaviour of ASP Classic's Response.End() and Response.Redirect methods.

However.

It seems intermittently in our application that the exception bubbles too high. For example, we have a page that is called from client side javascript to return a small string to display in a page.

protected void Page_Load(object sender, EventArgs e)
{
      // Work out some stuff.
      Response.Write(stuff);
      Response.End();
}

This generally works, but sometimes, we get the exception bubbling up to the UI layer and get part of the exception text displayed in the page.

Similarly, else where we have:

// check the login is still valid:
if(!loggedin) {
  Response.Redirect("login.aspx");
}

In some cases, the user is redirected to login.aspx, in others, the user gets an ASP.NET error page and stack dump (because of how our dev servers are configured).

i.e. in some cases, response.redirect throws an exception all the way up INSTEAD of doing a redirect. Why? How do we stop this?

Upvotes: 2

Views: 946

Answers (3)

spaark
spaark

Reputation: 711

Since I was looking for an answer to this question too, I am posting what seams to me a complete solution, rounding up the two above answers:

public static void Redirect(this TemplateControl control, bool ignoreIfInvisible = true)
{
  Page page = control.Page;
  if (!ignoreIfInvisible || page.Visible)
  {
    // Sets the page for redirect, but does not abort.
    page.Response.Redirect(url, false);
    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline
    // chain of execution and directly execute the EndRequest event.
    HttpContext.Current.ApplicationInstance.CompleteRequest();

    // By setting this to false, we flag that a redirect is set,
    // and to not render the page contents.
    page.Visible = false;
  }
}

Source: http://www.codeproject.com/Tips/561490/ASP-NET-Response-Redirect-without-ThreadAbortExcep

Upvotes: 0

Ryan Shripat
Ryan Shripat

Reputation: 5704

You can use the following best-practice code instead, as explained by this answer to prevent the exception from happening in the first place:

Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();

Upvotes: 1

Damien Dennehy
Damien Dennehy

Reputation: 4074

Have you tried overloading the default Redirect method and not ending the response?

if(!loggedin) { 
     Response.Redirect("login.aspx", false); 
} 

Upvotes: 1

Related Questions