如果使用 Response.End、Response.Redirect 或 Server.Transfer,则会发生 ThreadAbortException

本文可帮助你解决 ThreadAbortException 使用 Response.End时发生的错误, Response.Redirect或者 Server.Transfer

原始产品版本: 在 .NET Framework 4.6.2 或更高版本上 ASP.NET,ASP.NET .NET Framework 3.5 Service Pack 1
原始 KB 数: 312629

现象

如果使用 ,Response.EndResponse.RedirectServer.Transfer方法ThreadAbortException将发生异常。 可以使用 try-catch 语句捕获此异常。

原因

该方法 Response.End 结束页面执行,并将执行转移到应用程序事件管道中的Application_EndRequest事件。 不会执行以下 Response.End 代码行。

此问题发生在方法中 Response.RedirectServer.Transfer 因为两种方法都在内部调用 Response.End。

解决方法

若要解决此问题,请使用以下方法之一:

  • 因此 Response.End ,调用 HttpContext.Current.ApplicationInstance.CompleteRequest 该方法, Response.End 而不是绕过对 Application_EndRequest 事件的代码执行。

  • 对于 Response.Redirect,请使用重载 Response.Redirect(String url, bool endResponse),该重载传递了 endResponse 参数的 false 以禁止对内部调用 Response.End。 例如:

    Response.Redirect ("nextpage.aspx", false);
    

    如果使用此解决方法,则执行以下 Response.Redirect 代码。

  • 对于 Server.Transfer,请改用该方法 Server.Execute

尽管 ASP.NET 处理此异常,但可以使用 try-catch 语句捕获此异常。 例如:

try
{
    Response.Redirect("nextpage.aspx");
}
catch (Exception ex)
{
    Response.Write (ex.Message);
}

Response.Write 行中添加断点,并注意到此断点已命中。 检查异常时,请注意异常 ThreadAbortException 发生。