在 ASP.NET 開發中,Cookie 是維持用戶狀態、儲存偏好設定的常用機制。但原生 HttpCookie 操作較為繁瑣,特別是處理子鍵值集合、過期時間、刪除邏輯時容易出錯。本文提供一個完整的 CookieFramework 靜態類別(VB.NET 實作),封裝了寫入單一 Cookie、寫入 Cookie 集合、讀取、刪除等核心功能,開箱即用,大幅簡化開發流程。
Imports System.Web.HttpContext
Public Class CookieFramework
' 寫入單一 Cookie
Public Shared Function WriteCookie(ByVal CookieName As String,
ByVal CookieValue As String, ByVal ExpiresDate As Integer) As Boolean
Dim aCookie As New HttpCookie(CookieName)
aCookie.Value = CookieValue
aCookie.Expires = DateTime.Now.AddDays(ExpiresDate)
System.Web.HttpContext.Current.Response.Cookies.Add(aCookie)
End Function
' 寫入 Cookie 子鍵值集合
Public Shared Function WriteCookies(ByVal CookieName As String,
ByVal CookieItem As String, ByVal ItemValue As String,
ByVal ExpiresDate As Integer) As Boolean
Dim aCookie As HttpCookie
If Current.Request.Cookies(CookieName) Is Nothing Then
aCookie = New HttpCookie(CookieName)
Else
aCookie = Current.Request.Cookies(CookieName)
End If
aCookie.Values(CookieItem) = ItemValue
aCookie.Expires = DateTime.Now.AddDays(ExpiresDate)
System.Web.HttpContext.Current.Response.Cookies.Add(aCookie)
End Function
' ... 其餘方法同理封裝
End Class
' 寫入用戶偏好語言,保留 30 天
CookieFramework.WriteCookie("UserLang", "zh-TW", 30)
' 寫入購物車多項商品
CookieFramework.WriteCookies("Cart", "Item001", "2", 7)
CookieFramework.WriteCookies("Cart", "Item002", "1", 7)
' 讀取
Dim lang As String = CookieFramework.ReadCookie("UserLang")
Dim qty As String = CookieFramework.ReadCookies("Cart", "Item001")
此封裝類別已在多個實務專案驗證,穩定可靠,建議納入專案共用函式庫,統一管理 Cookie 操作邏輯。