萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 網頁傳值完整指南:QueryString、Session、Cookie、Application、Server.Transfer

前言

ASP.NET Web Forms 頁面間傳遞資料有多種方式,各有適用場景、生命週期與安全性考量。本文整理五大主流方法並提供完整範例。

傳值方式比較表

方式儲存位置生命週期適用場景安全性
QueryStringURL單次請求非敏感、可書籤、分享連結低 (明文、可竄改)
Session伺服器記憶體/資料庫工作階段 (預設 20 分鐘)使用者狀態、購物車、權限中 (需防 Session Hijacking)
Cookie用戶端瀏覽器設定 Expires 可持久記住我、偏好設定、追蹤低 (可竄改、XSS 風險)
Application伺服器記憶體應用程式存活期間全域計數器、快取共用資料中 (需 Lock/Unlock)
Server.Transfer伺服器端記憶體 (Context)單次請求同一應用程式內頁面轉移、保留表單資料高 (不經瀏覽器)

完整範例:WebForm1.aspx → WebForm2.aspx

1. QueryString (GET)

// 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
}

2. Session

// 送出
Session["UserName"] = txtUser.Text;
Session["Password"] = txtPwd.Text; // 實務切勿存明文密碼!
Server.Transfer("WebForm2.aspx"); // 或 Response.Redirect

// 接收
string user = Session["UserName"]?.ToString();
Session.Remove("UserName"); // 用完移除

3. Cookie

// 送出
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"];

4. Application (全域共用)

// 送出
Application.Lock();
Application["OnlineUsers"] = (int)(Application["OnlineUsers"] ?? 0) + 1;
Application.UnLock();
Response.Redirect("WebForm2.aspx");

// 接收
int count = (int)(Application["OnlineUsers"] ?? 0);

5. Server.Transfer (保留 Context)

// 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}";
    }
}

安全性最佳實務

  • 敏感資料勿用 QueryString/Cookie:密碼、Token、個資請用 Session 或加密 Token。
  • Cookie 設定 HttpOnly + Secure:cookie.HttpOnly = true; cookie.Secure = true; (需 HTTPS)。
  • Session 防竄改:ASP.NET 自動簽章 SessionID,但仍需注意 Session Fixation (登入後重新產生 SessionID)。
  • 驗證輸入:接收端務必檢查 null、長度、格式,防止 XSS 與邏輯錯誤。
copyright © 萬盛學電腦網 all rights reserved