HttpContext.Items 屬性提供一個鍵/值集合,生命週期僅限於**單一 HTTP 請求處理期間**。請求結束後自動清除,極適合在同一請求的不同模組(IHttpModule、IHttpHandler、頁面、User Control)間傳遞資料。
// 頁面 A.aspx - 點擊按鈕轉向 B.aspx
public void Submit_Click(Object sender, EventArgs E) {
SqlConnection conn = new SqlConnection("...");
SqlDataAdapter da = new SqlDataAdapter("select * from Authors", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Authors");
// 存入暫存
Context.Items["MyData"] = ds;
Server.Transfer("B.aspx");
}
// 頁面 B.aspx - 讀取暫存
public void Page_Load(Object sender, EventArgs E) {
if (!IsPostBack) {
DataSet ds = (DataSet)Context.Items["MyData"];
// 後續處理...
}
}
| 優點 | 缺點 |
|---|---|
| 無需 Session/Application 鎖定開銷 | 僅限單一請求,不支援跨請求 |
| 自動清理,無記憶體洩漏風險 | Server.Transfer 時 URL 不變,書籤/重新整理易混淆 |
| 型別任意,靈活度高 | 大量資料仍佔用請求執行緒記憶體 |