Response.Redirect() ThreadAbortException Bubbling Too High Intermittently

*爱你&永不变心* 提交于 2020-01-24 12:40:46

问题


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?


回答1:


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

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



回答2:


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();



回答3:


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



来源:https://stackoverflow.com/questions/3213641/response-redirect-threadabortexception-bubbling-too-high-intermittently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!