标签:
首先是一些概念
接下来是网上找的一个CookieHelper:
using System; using System.Collections.Generic; using System.Web; public class CookieHelper { /// <summary> /// 写入 /// </summary> /// <param name="n">cookie名</param> /// <param name="d">保存天数</param> /// <param name="l">需要保存的列表的值</param> public static void WriteIn(string n, int d, Dictionary<string, string> l) { var cookie = new HttpCookie(n); //初使化并设置Cookie的名称 var dt = DateTime.Now; var ts = new TimeSpan(d, 0, 0, 0, 0); //过期时间为d天 cookie.Expires = dt.Add(ts); //设置过期时间 foreach (var item in l) { cookie.Values.Add(item.Key, item.Value); } HttpContext.Current.Response.AppendCookie(cookie); } /// <summary> /// 单个读出 /// </summary> /// <param name="n">cookie名</param> /// <param name="v">第X个值</param> /// <returns></returns> public static string Read(string n, string v) { return HttpContext.Current.Request.Cookies[n][v]; } /// <summary> /// 修改 /// </summary> /// <param name="n">cookie名</param> /// <param name="c">需要修改的索引</param> /// <param name="v">需要修改的值</param> public static void ReWrite(string n, string c, string v) { //获取客户端的Cookie对象 var cok = HttpContext.Current.Request.Cookies[n]; if (cok != null) { cok.Values[c] = v; HttpContext.Current.Response.AppendCookie(cok); } } /// <summary> /// 新增 /// </summary> /// <param name="n">cookie名</param> /// <param name="c">索引</param> /// <param name="v">值</param> public static void Add(string n, string c, string v) { //获取客户端的Cookie对象 var cok = HttpContext.Current.Request.Cookies[n]; if (cok != null) { //往Cookie里加入新的内容 cok.Values.Set(c, v); HttpContext.Current.Response.AppendCookie(cok); } } /// <summary> /// 去除 /// </summary> /// <param name="n">cookie名</param> /// <param name="c">索引</param> public static void Remove(string n, string c) { var cok = HttpContext.Current.Request.Cookies[n]; if (cok != null) { cok.Values.Remove(c); //移除 HttpContext.Current.Response.AppendCookie(cok); } } /// <summary> /// 删除 /// </summary> /// <param name="n">cookie名</param> public static void Delete(string n) { var cok = HttpContext.Current.Request.Cookies[n]; if (cok != null) { var ts = new TimeSpan(-1, 0, 0, 0); cok.Expires = DateTime.Now.Add(ts); //通过设置过期时间,删除整个Cookie HttpContext.Current.Response.AppendCookie(cok); } } }
标签:
原文地址:http://www.cnblogs.com/FangZhaohu/p/4575911.html