在 AJAX 請求處理中呼叫 Response.End(),Visual Studio 偵錯時顯示:
由於代碼已經過優化或者本機框架位於調用堆棧之上,無法計算表達式的值。
實際拋出的是 ThreadAbortException。
Response.End() 內部呼叫 Thread.CurrentThread.Abort() 強制終止當前執行緒。ThreadAbortException,中斷後續程式碼,直接跳轉至 Application_EndRequest 事件。Response.Redirect、Server.Transfer 內部也呼叫 Response.End(),同樣會觸發此異常。public void Write(string obj) {
Response.Clear();
Response.Write(obj);
HttpContext.Current.ApplicationInstance.CompleteRequest(); // 關鍵:不終止執行緒
// Response.End(); // 註釋掉
}
CompleteRequest() 會跳過剩餘的頁面生命週期事件(如 PreRender、Render),直接進入 EndRequest,但不會中止執行緒,後續代碼仍會繼續執行。// 錯誤:Response.Redirect("next.aspx"); // 內部呼叫 End()
// 正確:
Response.Redirect("next.aspx", false); // 第二個參數 false = 不呼叫 Response.End()
HttpContext.Current.ApplicationInstance.CompleteRequest(); // 手動完成請求
try {
Response.End();
} catch (ThreadAbortException) {
// Thread.ResetAbort(); // 可選:阻止異常繼續傳播
}
缺點:掩蓋真實錯誤、影響效能、違反異常處理最佳實踐。
| 場景 | 推薦做法 |
|---|---|
| AJAX/JSON 回應 | Response.Write(json); CompleteRequest(); |
| 頁面重導向 | Response.Redirect(url, false); CompleteRequest(); |
| 檔案下載 | Response.BinaryWrite(bytes); CompleteRequest(); |
| 傳統 WebForm 完整頁面 | 正常流程結束,無需呼叫 End/CompleteRequest |
Response.End() 是 ASP.NET 1.x 遺留的強制終止機制,現代開發應全面改用 HttpApplication.CompleteRequest(),避免執行緒中止帶來的效能損耗、日誌雜訊與偵錯困擾。