Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

ASP Response.Redirect 頁面重導向完整應用指南

編輯:關於伺服器

核心語法

Response.Redirect "target_url"

關鍵限制:緩衝區機制

Response.Redirect 必須在任何輸出發送給瀏覽器之前執行。若已有 HTML/空白字元輸出,將拋出「標頭已送出」錯誤。

三種解決方案

方案 1:置於頁面最頂端(最簡單)

<% 
If Session("CustomerID") = 0 Then 
    Response.Redirect "homepage.asp" 
End If 
%>
<html><body>...

方案 2:啟用 Response.Buffer

<% Response.Buffer = True %>
<html><body>
<% 
' 業務邏輯...
If Request("FName") = "" Then
    Response.Clear
    Response.Redirect "../test.html"
Else
    Response.Write Request("FName")
End If
%>
</body></html>

Response.Buffer = True 會暫存所有輸出,直到腳本結束或呼叫 Response.Flush/End。

方案 3:Server.Transfer(同站內轉向)

Server.Transfer "/internal/page.asp"
  • 瀏覽器網址列不變更
  • 保留原頁面所有內建物件狀態
  • 適用於同一應用程式內的伺服器端轉向

Server 物件常用方法速查

方法用途
CreateObject建立 COM 元件實例
Execute執行另一 ASP 檔案(如函式庫調用)
GetLastError取得 ASPError 物件(錯誤處理頁面用)
HTMLEncodeHTML 編碼防 XSS
MapPath相對路徑轉絕對物理路徑
Transfer伺服器端轉向(保留狀態)
URLEncodeURL 編碼

MapPath 實用範例

<%= Server.MapPath(Request.ServerVariables("PATH_INFO")) %>
' 輸出:C:\Inetpub\wwwroot\script\test.asp

<%= Server.MapPath("data.txt") %>
' 相對當前目錄:C:\Inetpub\wwwroot\script\data.txt

<%= Server.MapPath("/script/data.txt") %>
' 相對網站根目錄:C:\Inetpub\wwwroot\script\data.txt

ScriptTimeout 設定

<% Server.ScriptTimeout = 120 %>  ' 設為 120 秒
<% Timeout = Server.ScriptTimeout %>  ' 讀取目前值

註:不可小於 IIS 管理介面設定的預設值。

最佳實踐建議

  • 登入驗證、權限檢查放在頁面最上方,搭配 Response.Buffer = True
  • 避免在大量 HTML 輸出後才判斷重導向
  • 跨網域重導向請使用完整 URL(含 https://)
  • 錯誤處理頁面建議使用 Server.GetLastError + Server.Transfer
Copyright © Windows教程網 All Rights Reserved