Response.Redirect 是 ASP.NET Web Forms 最常用的頁面導向方式,本文涵蓋基本跳轉、查詢字串參數傳遞、目標頁面接收參數、以及常見陷阱與替代方案。
protected void LinkButton1_Click(object sender, EventArgs e)
{
string url = "InfoShow.aspx";
Response.Redirect(url);
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
string userName = e.Item.Value.Trim();
string url = "InfoRelease.aspx?UserName=" + Server.UrlEncode(userName);
Response.Redirect(url);
}
Server.UrlEncode 編碼參數值,防止特殊字元破壞 URL。& 串接:?a=1&b=2。protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userName = Request.QueryString["UserName"]; // 建議用 QueryString 而非 Request["Key"]
if (!string.IsNullOrEmpty(userName))
{
txtInfoclass.Text = userName;
}
}
}
Request.QueryString["Key"] 明確從查詢字串取值,避免與 Form、Cookies、ServerVariables 衝突。null 或 String.IsNullOrEmpty。| 多載 | 行為 |
|---|---|
Redirect(url) | 送出 302 回應,嘗試終止目前執行緒(拋出 ThreadAbortException),後續程式碼不執行。 |
Redirect(url, false) | 送出 302 回應,不終止執行緒,後續程式碼繼續執行。需自行 return 或 CompleteRequest()。 |
Redirect(url) 會拋出此例外,若在 try-catch 捕捉 Exception 並吞掉,會導致導向失敗。解決:捕捉時重新拋出 throw; 或使用 Redirect(url, false) 配合 Context.ApplicationInstance.CompleteRequest()。~/ 僅伺服器端控件識別,Redirect 需解析為絕對路徑:ResolveUrl("~/InfoShow.aspx") 或 VirtualPathUtility.ToAbsolute("~/InfoShow.aspx")。Session、TempData (MVC)、資料庫暫存或 POST 重導向模式 (PRG)。Redirect 會失敗,需觸發完整回發或使用 ScriptManager.RegisterStartupScript 輸出 window.location.href。Server.Transfer("Target.aspx", true); // 保留 QueryString/Form
Context.Handler (PreviousPage) 取得控件值。