Cookie 是伺服器在用戶端儲存少量資料的機制。ASP 透過 Response.Cookies 寫入、Request.Cookies 讀取。本文涵蓋單值/多值 Cookie、Expires/Path/Domain/Secure/HttpOnly 屬性設定、刪除技巧與安全最佳實務。
' 寫入單值
Response.Cookies("username") = "Kevin"
Response.Cookies("username").Expires = DateAdd("d", 30, Now()) ' 30 天有效
' 寫入多值 (子鍵)
Response.Cookies("user")("name") = "Kevin"
Response.Cookies("user")("role") = "admin"
Response.Cookies("user").Expires = DateAdd("d", 30, Now())
' 讀取
Dim uName, uRole
uName = Request.Cookies("username")
uRole = Request.Cookies("user")("role")
Response.Write "Name: " & uName & ", Role: " & uRole
| 屬性 | 說明 | 範例 |
|---|---|---|
Expires | 過期日期 (GMT),過期自動刪除 | DateAdd("d",30,Now()) |
Path | 生效路徑,預設為應用程式根目錄 | Response.Cookies("c").Path = "/" |
Domain | 生效網域,支援子網域共享 | Response.Cookies("c").Domain = ".example.com" |
Secure | 僅 HTTPS 傳輸 | Response.Cookies("c").Secure = True |
HttpOnly | 禁止 JavaScript 存取 (防 XSS 竊取) | ASP 原生不支援,需手寫 Header |