ASP.NET Web Forms 頁面間傳遞資料有多種方式,各有適用場景、生命週期與安全性考量。本文整理五大主流方法並提供完整範例。
| 方式 | 儲存位置 | 生命週期 | 適用場景 | 安全性 |
|---|---|---|---|---|
| QueryString | URL | 單次請求 | 非敏感、可書籤、分享連結 | 低 (明文、可竄改) |
| Session | 伺服器記憶體/資料庫 | 工作階段 (預設 20 分鐘) | 使用者狀態、購物車、權限 | 中 (需防 Session Hijacking) |
| Cookie | 用戶端瀏覽器 | 設定 Expires 可持久 | 記住我、偏好設定、追蹤 | 低 (可竄改、XSS 風險) |
| Application | 伺服器記憶體 | 應用程式存活期間 | 全域計數器、快取共用資料 | 中 (需 Lock/Unlock) |
| Server.Transfer | 伺服器端記憶體 (Context) | 單次請求 | 同一應用程式內頁面轉移、保留表單資料 | 高 (不經瀏覽器) |
// WebForm1.aspx.cs - 送出
protected void btnQueryString_Click(object sender, EventArgs e)
{
string url = $"WebForm2.aspx?un={Server.UrlEncode(txtUser.Text)}&pwd={Server.UrlEncode(txtPwd.Text)}";
Response.Redirect(url);
}
// WebForm2.aspx.cs - 接收
protected void Page_Load(object sender, EventArgs e)
{
string user = Request.QueryString["un"];
string pwd = Request.QueryString["pwd"];
// 注意:Request.QueryString 自動 UrlDecode
}
// 送出
Session["UserName"] = txtUser.Text;
Session["Password"] = txtPwd.Text; // 實務切勿存明文密碼!
Server.Transfer("WebForm2.aspx"); // 或 Response.Redirect
// 接收
string user = Session["UserName"]?.ToString();
Session.Remove("UserName"); // 用完移除
// 送出
var cookie = new HttpCookie("LoginInfo");
cookie.Values["UserName"] = txtUser.Text;
cookie.Values["Password"] = txtPwd.Text;
cookie.Expires = DateTime.Now.AddDays(7); // 持久化
Response.Cookies.Add(cookie);
Response.Redirect("WebForm2.aspx");
// 接收
string user = Request.Cookies["LoginInfo"]?["UserName"];
// 送出
Application.Lock();
Application["OnlineUsers"] = (int)(Application["OnlineUsers"] ?? 0) + 1;
Application.UnLock();
Response.Redirect("WebForm2.aspx");
// 接收
int count = (int)(Application["OnlineUsers"] ?? 0);
// WebForm1.aspx.cs
public string UserName => txtUser.Text;
public string Password => txtPwd.Text;
protected void btnTransfer_Click(object sender, EventArgs e)
{
Server.Transfer("WebForm2.aspx"); // URL 不變,Context 保留
}
// WebForm2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
// 取得上一頁公開屬性
var prev = Context.Handler as WebForm1;
if (prev != null)
{
lblInfo.Text = $"User: {prev.UserName}, Pwd: {prev.Password}";
}
}
cookie.HttpOnly = true; cookie.Secure = true; (需 HTTPS)。