如果使用 Response.End、Response.Redirect 或 Server.Transfer,则会发生 ThreadAbortException
- 项目
- 2023/07/17
- 3 个参与者
反馈
本文内容
本文可帮助你解决使用或Server.Transfer使用Response.EndResponse.Redirect时发生的 ThreadAbortException 错误。
原始产品版本:.NET Framework 4.5.2 上 ASP.NET,.NET Framework 3.5 Service Pack 1 上 ASP.NET
原始 KB 编号: 312629
症状
如果使用 ThreadAbortException Response.EndResponse.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 (字符串 url,bool endResponse) ,为 endResponse 参数传递 false 以抑制内部调用Response.End。 例如:ASP.NET (C#)复制
Response.Redirect ("nextpage.aspx", false);如果使用此解决方法,则会执行以下
Response.Redirect代码。 -
对于
Server.Transfer,请改用该Server.Execute方法。
尽管 ASP.NET 处理此异常,但可以使用该 try-catch 语句来捕获此异常。 例如:
C#复制
try
{
Response.Redirect("nextpage.aspx");
}
catch (Exception ex)
{
Response.Write (ex.Message);
}
在行上 Response.Write 添加断点,并注意此断点已命中。 检查异常时,请注意 ThreadAbortException 异常发生。

本文详细描述了在ASP.NET中使用Response.End、Response.Redirect和Server.Transfer时可能出现的ThreadAbortException问题,提供了使用HttpContext.Current.ApplicationInstance.CompleteRequest和Response.Redirect重载的方法以及如何捕获异常的解决方案。
237

被折叠的 条评论
为什么被折叠?



