如果使用 Response.End、Response.Redirect 或 Server.Transfer,则会发生 ThreadAbortException
本文可帮助你解决在使用 Response.End
、 Response.Redirect
或 Server.Transfer
时出现的 ThreadAbortException 错误。
原始产品版本:.NET Framework 4.5.2 上的 ASP.NET,ASP.NET.NET Framework 3.5 Service Pack 1
原始 KB 编号: 312629
症状
如果使用 Response.End
、 Response.Redirect
或 Server.Transfer
方法,则会发生 ThreadAbortException 异常。 可以使用 语句 try-catch
来捕获此异常。
原因
方法 Response.End
结束页面执行,并将执行转移到应用程序事件管道中的 Application_EndRequest 事件。 不执行以下 Response.End
代码行。
此问题发生在 和 Server.Transfer
方法中,Response.Redirect
因为这两种方法都在内部调用 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 异常。
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈