多角色電商系統 (買家、賣家、代理商、管理員等) 需建立不同域名、不同內容的 Cookie。重複撰寫 Cookie 程式碼冗長且易出錯,故封裝通用類別。
// 設定 Cookie
public void SetCookies(string domain, string type, XieGou.XGMap map) {
HttpCookie cookie = new HttpCookie(type);
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(1,0,0,0); // 有效 1 天
cookie.Expires = dt.Add(ts);
cookie.Domain = domain;
for (int i = 0; i < map.Size(); i++) {
cookie.Values.Add(map.GetTag(i), map.GetValue(i).ToString());
}
HttpContext.Current.Response.AppendCookie(cookie);
}
// 讀取 Cookie
public string GetCookies(string type, string name) {
if (HttpContext.Current.Request.Cookies[type] != null) {
if (HttpContext.Current.Request.Cookies[type].Values[name] != null) {
return HttpContext.Current.Request.Cookies[type].Values[name].ToString();
}
}
return "0";
}
XieGou.XGMap map = new XGMap();
map.Add("shopid", shop.Id.ToString());
map.Add("shopname", shop.Name);
func.SetCookies(".shopxg.com", "shopxg_namespace", map);
Map 類別動態傳遞鍵值對,減少重複程式碼。.domain.com 共享 Cookie)。