using System; using System.Globalization; using static System.Web.Configuration.WebConfigurationManager; using System.Web; namespace CommonTool { /// /// Cookie帮助类 /// public class CookieHelper { public static CookieHelper Instance { get; } = new CookieHelper(); /// /// 写cookie值 /// /// 名称 /// 值 public void WriteCookie(string strName, string strValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName] ?? new HttpCookie(strName); cookie.Value = strValue; HttpContext.Current.Response.AppendCookie(cookie); } /// /// 写cookie值 /// /// 名称 /// 值 /// 过期时间(分钟) public void WriteCookie(string strName, string strValue, int expires) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName] ?? new HttpCookie(strName); cookie.Value = strValue; cookie.Expires = DateTime.Now.AddMinutes(expires); HttpContext.Current.Response.AppendCookie(cookie); } /// /// 读cookie值 /// /// 名称 /// cookie值 public string GetCookie(string strName) { if (HttpContext.Current.Request.Cookies[strName] != null) { return HttpContext.Current.Request.Cookies[strName].Value; } return ""; } /// /// Get cookie expiry date that was set in the cookie value /// /// /// public DateTime GetExpirationDate(HttpCookie cookie) { if (String.IsNullOrEmpty(cookie.Value)) { return DateTime.MinValue; } string strDateTime = cookie.Value.Substring(cookie.Value.IndexOf("|", StringComparison.Ordinal) + 1); return Convert.ToDateTime(strDateTime); } /// /// Set cookie value using the token and the expiry date /// /// /// /// public string BuildCookueValue(string value, int minutes) { return $"{value}|{DateTime.Now.AddMinutes(minutes).ToString(CultureInfo.InvariantCulture)}"; } /// /// Reads cookie value from the cookie /// /// /// public string GetCookieValue(HttpCookie cookie) { if (cookie!=null) { if (String.IsNullOrEmpty(cookie.Value)) return cookie.Value; return cookie.Value.Substring(0, cookie.Value.IndexOf("|", StringComparison.Ordinal)); } return null; } public void DelCookie(string strName) { WriteCookie(strName, "", -10000); } public SysUserInfo GetSysUserInfo(string pcCookieName) { string lcCookieName = pcCookieName?? AppSettings["SysUserInfoCookie"]; string lcCookieValue = GetCookieValue(HttpContext.Current.Request.Cookies[lcCookieName]); try { return JsonHelper.Instance.Deserialize(SysSecurity.Decrypt(lcCookieValue)); } catch { return null; } } } }