对cookie操作不太熟悉的可以参考一下。
一般来说 cookie是个针对访问者电脑存储数据的东西,可以把一个cookie看作一个表,有表名,可以有很多行,每一行有两个字段,key和value,key唯一,可以通过key找到对应的值 value.
封装方法:
#region 设置cookie /// <summary> /// 设置cookie /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="cookiename">cookie名称</param> /// <param name="cookiedays">cookie保留多少天(默认3天),可以用小数表示</param> public static void SetCookies(HttpResponseBase Response, HttpRequestBase Request, string key, string value, string cookiename,double cookiedays=3) { HttpCookie cookie = Request.Cookies[cookiename]; //cookie.ExpirationSet = false; if (cookie == null) { cookie = new HttpCookie(cookiename); cookie.Values.Add(key, value); } else { if (cookie.Values[key] != null) { cookie[key] = value; } else cookie.Values.Add(key, value); } if (HttpContext.Current != null) { if (HttpContext.Current.Request.Url.DnsSafeHost.Contains("kinpan.com")) { cookie.Domain = "kinpan.com"; } } //cookie.Domain = ConfigurationManager.AppSettings["kinpandomain"]; cookie.Path = "/"; cookie.Expires = DateTime.Now.AddDays(cookiedays); Response.Cookies.Remove(cookiename); Response.Cookies.Add(cookie); } #endregion #region 删除cookie /// <summary> /// 删除cookie,我们没有直接删除的权限,但是新建一个同名cookie,设置为过期,那么浏览器会去检测和删除同名的cookie。 /// </summary> /// <param name="cookiename">cookie名称</param> public static void deleteCookie(HttpResponseBase Response,string cookiename) { if (cookiename.HasValue()) { HttpCookie aCookie = new HttpCookie(cookiename); aCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(aCookie); } } #endregion #region 获取整个cookie /// <summary> /// 获取整个cookie /// </summary> /// <param name="cookiename"></param> /// <returns></returns> public static HttpCookie GetCookie(HttpRequestBase Request, string cookiename) { return HttpContext.Current.Request.Cookies[cookiename]; } #endregion #region 获取cookie里的键对应的值 /// <summary> /// 获取cookie里的键对应的值 /// </summary> /// <param name="name">名称</param> /// <param name="key">键</param> /// <returns>返回键对应的值</returns> public static string GetCookies(HttpRequestBase Request, string name, string key) { if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(key)) { return String.Empty; } else { HttpCookie cookie = Request.Cookies[name]; if (cookie != null && cookie[key] != null) { string value = cookie[key].ToString(); return HttpContext.Current.Server.UrlDecode(value); } else { return String.Empty; } } } #endregion
时间: 2024-10-09 13:27:53