Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
 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);
 }
Exemplo n.º 3
0
        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));
        }
Exemplo n.º 4
0
        /// <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));
        }