public static void CreateCookie <T>( T cookieObject, string key, DateTime?expiredTime = null, Func <T, string> resolveObjectToStr = null, bool isSecurity = true) { var newCookie = new HttpCookie(key); string cookieValue = null; cookieValue = cookieObject is string ?Convert.ToString(cookieObject) : resolveObjectToStr?.Invoke(cookieObject); if (string.IsNullOrEmpty(cookieValue)) { throw new NullReferenceException("set cookie value is null"); } newCookie.Value = cookieValue; if (expiredTime.HasValue) { newCookie.Expires = expiredTime.Value; } if (isSecurity) { newCookie = CookieSecure.Encode(newCookie); } HttpContext.Current?.Response.Cookies.Add(newCookie); }
private AccessTokenData GetAccessToken() { if (HttpContext.Current.Request.Cookies.AllKeys.Contains(AccessTokenKey)) { var cookie = HttpContext.Current.Request.Cookies[AccessTokenKey]; var decrypted = CookieSecure.Decode(cookie, CookieProtection.Encryption); return(!string.IsNullOrEmpty(decrypted.Value) ? JsonConvert.DeserializeObject <AccessTokenData>(decrypted.Value) : null); } return(null); }
private void SetAccessToken(AccessTokenData accessToken) { var cookie = new HttpCookie(AccessTokenKey) { HttpOnly = true, Expires = DateTime.Today.AddSeconds(accessToken.ExpiresIn), Value = JsonConvert.SerializeObject(accessToken) }; HttpContext.Current.Response.SetCookie(CookieSecure.Encode(cookie, CookieProtection.Encryption)); }
/// <summary> /// 获取Cookie值,并且反序列化为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public static T GetValue <T>(string key, bool isSecurity = true) { var existCookie = HttpContext.Current?.Request.Cookies[key]; if (existCookie == null || string.IsNullOrEmpty(existCookie.Value)) { return(default(T)); } existCookie = isSecurity ? CookieSecure.Decode(existCookie) : existCookie; if (typeof(T) == typeof(string)) { return((T)(object)existCookie.Value); } return(JsonConvert.DeserializeObject <T>(existCookie.Value)); }