如果您使用 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 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應