/// <summary> /// Set cookie /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <param name="expiredDate"></param> public static void SetCookie <T>(string name, T value, DateTime?expiredDate = null) { if (HttpContext.Current != null) { //Create cookie HttpCookie cookie; if (typeof(T) == typeof(string)) { cookie = new HttpCookie(name, value.ToString()); } else { var cookieValue = SerializeUtilities.Serialize(value); cookie = new HttpCookie(name, cookieValue); } //Set expired date if (!expiredDate.HasValue) { expiredDate = DateTime.UtcNow.AddDays(1); } cookie.Expires = expiredDate.Value; cookie.Path = "/"; HttpContext.Current.Response.Cookies.Set(cookie); } }
/// <summary> /// Get cookie by name /// </summary> /// <param name="name"></param> /// <param name="defaultValue"></param> /// <param name="setCookie"></param> /// <param name="expiredDate"></param> public static T GetCookie <T>(string name, T defaultValue = default(T), bool setCookie = false, DateTime?expiredDate = null) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(); } if (HttpContext.Current != null) { //May be cookie name has been encode, need to encode the input too var encodeName = HttpUtility.UrlEncode(name); var cookieName = HttpContext.Current.Request.Cookies.AllKeys.FirstOrDefault( k => k.Equals(name, StringComparison.CurrentCultureIgnoreCase) || k.Equals(encodeName, StringComparison.CurrentCultureIgnoreCase)); if (cookieName != null) { var cookie = HttpContext.Current.Request.Cookies[cookieName]; if (cookie != null) { return(SerializeUtilities.Deserialize <T>(cookie.Value)); } } } //Set default value if cookie is not found if (setCookie) { SetCookie(name, defaultValue, expiredDate); } return(defaultValue); }