【问题标题】:Response.Redirect() ThreadAbortException Bubbling Too High IntermittentlyResponse.Redirect() ThreadAbortException 间歇性冒泡过高
【发布时间】:2010-07-09 14:37:05
【问题描述】:

我(现在)理解 Response.Redirect() 和 Response.End() 抛出 ThreadAbortException 作为杀死当前处理线程以模拟 ASP Classic 的 Response.End() 和 Response.Redirect 方法的行为的昂贵方式.

但是。

在我们的应用程序中似乎间歇性地出现异常气泡过高。例如,我们有一个从客户端 javascript 调用的页面,以返回一个小字符串以显示在页面中。

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

这通常有效,但有时,我们会将异常冒泡到 UI 层并在页面中显示部分异常文本。

同样,我们有其他地方:

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

在某些情况下,用户会被重定向到 login.aspx,而在其他情况下,用户会收到 ASP.NET 错误页面和堆栈转储(因为我们的开发服务器的配置方式)。

即在某些情况下,response.redirect 会一直抛出异常而不是进行重定向。为什么?我们如何阻止这种情况?

【问题讨论】:

    标签: asp.net exception response.redirect


    【解决方案1】:

    您是否尝试过重载默认的 Redirect 方法而不结束响应?

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

    【讨论】:

    • 通过一些研究得出了正确的做法,但是,仍然想了解为什么有时它会冒出异常而其他情况下它会起作用。
    • 为什么还要使用 Response.Write() 将文本写入页面?这不是推荐的方法 - 它比 ASP.NET 更经典的 ASP。
    【解决方案2】:

    您可以改用以下最佳实践代码 as explained by this answer 来防止异常发生:

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

    【讨论】:

    • 但这并没有保留我的查询字符串。当页面被重定向时它被删除
    【解决方案3】:

    由于我也在寻找这个问题的答案,所以我发布了一个完整的解决方案,总结了上述两个答案:

    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;
      }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2011-08-19
      • 2012-04-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2021-07-16
      • 2016-02-23
      相关资源
      最近更新 更多