以前Insus.NET有在博客上有写过一篇《》
昨天Insus.NET有在命名用这方法的专项中,进行改写与优化。
把Cookie类抽出并独立起来。
private static HttpResponse Response { get { return HttpContext.Current.Response; } } private static HttpRequest Request { get { return HttpContext.Current.Request; } }
这个cookie集合,当然存取单独cookie也行才对:
public static string GetCookie(string cookieName) { return Request.Cookies[cookieName] == null ? "" : Request.Cookies[cookieName].Value; } public static void SetCookie(string cookieName, string value) { Response.Cookies[cookieName].Value = value; } public static void RemoveCookie(string cookieName) { HttpCookie cookie = Request.Cookies[cookieName]; cookie.Expires = DateTime.Now.AddTicks(-1); Response.Cookies.Add(cookie); }
下面是存储cookie集合,即是说单个cookie中,能够存储多个键值:
private static DictionaryGetCookies(string cookieName) { Dictionary dic = new Dictionary (); if (Request.Cookies[cookieName] != null) { HttpCookie cookie = Request.Cookies[cookieName]; if (cookie != null) { NameValueCollection nvc = cookie.Values; foreach (string key in nvc.AllKeys) { dic.Add(key, cookie[key]); } } } return dic; } public static object GetCookies(string cookieName, string keyName) { Dictionary dic = GetCookies(cookieName); if (dic.Count > 0 && dic.ContainsKey(keyName)) { return dic[keyName]; } return null; } public static void SetCookies(string cookieName, Dictionary dic) { HttpCookie cookie = Request.Cookies[cookieName] == null ? new HttpCookie(cookieName) : Request.Cookies[cookieName]; foreach (KeyValuePair val in dic) { cookie[val.Key] = val.Value.ToString(); } Response.Cookies.Add(cookie); } public static void RemoveCookies(string cookieName) { HttpCookie cookie = Request.Cookies[cookieName]; cookie.Expires = DateTime.Now.AddTicks(-1); Response.AppendCookie(cookie); } public static void RemoveCookies(string cookieName, string keyName) { HttpCookie cookie = Request.Cookies[cookieName]; if (cookie != null) cookie.Values.Remove(keyName); Response.AppendCookie(cookie); }