/// <summary> /// 获取指定Cookie值 /// </summary> /// <param name="cookiename">cookiename</param> /// <param name="isencrypt">是否加密</param> /// <returns></returns> public static string GetCookieValue(string cookiename, bool isencrypt) { IsNullCookieName(cookiename); HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename]; string str = string.Empty; if (cookie != null) { str = isencrypt ? DEncryptHelper.Decrypt(HttpUtility.UrlDecode(cookie.Value)) : HttpUtility.UrlDecode(cookie.Value); } return(str); }
/// <summary> /// 添加或更新一个Cookie /// </summary> /// <param name="cookiename">cookie名</param> /// <param name="cookievalue">cookie值</param> /// <param name="expires">过期时间 DateTime</param> /// <param name="isencrypt">是否加密</param> public static void SetCookie(string cookiename, string cookievalue, DateTime?expires, bool isencrypt) { IsNullCookieName(cookiename); var cookie = new HttpCookie(cookiename) { Path = "/", //指定统一的Path,比便能通存通取 HttpOnly = true, //指定客户端脚本是否可以访问[默认为false] Domain = Domain, //设置跨域,这样在其它二级域名下就都可以访问到了 Value = isencrypt ? HttpUtility.UrlEncode(DEncryptHelper.Encrypt(cookievalue)) : HttpUtility.UrlEncode(cookievalue), }; if (expires != null) { cookie.Expires = (DateTime)expires;//expires==null 浏览器关闭时自动清除 } if (HttpContext.Current.Request.Cookies[cookiename] == null) { HttpContext.Current.Response.Cookies.Add(cookie); //添加Cookie } else { HttpContext.Current.Response.AppendCookie(cookie); //更新Cookie } }