C# 对cookies使用

        /// <summary>
        /// 增加Cookie的写入方法:
        /// </summary>
        /// <param name="cookieName">主键</param>
        /// <param name="cookieValue">键值</param>
        /// <param name="hours">有效时间(小时)</param>
        /// <returns></returns>
        public static bool SetCookie(string cookieName, string cookieValue, int hours)
        {
            try
            {
                HttpCookie Cookie = new HttpCookie(cookieName);
                if (!string.IsNullOrEmpty(Settings.Domain))
                    Cookie.Domain = Settings.Domain;
                Cookie.Expires = DateTime.Now.AddHours(hours);
                Cookie.Value = SecurityHelper.Encrypt(cookieValue);
                System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 读取Cookies
        /// </summary>
        /// <param name="CookieName">主键</param>
        /// <returns></returns>
        public static string GetCookie(string cookieName)
        {
            HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[cookieName];
            if (Cookie != null)
            {
                return SecurityHelper.Decrypt(Cookie.Value.ToString());
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 删除Cookies
        /// </summary>
        /// <param name="cookieName">主键</param>
        /// <returns></returns>
        public static bool DeleteCookie(string cookieName)
        {
            try
            {
                HttpCookie Cookie = new HttpCookie(cookieName);
                if (!string.IsNullOrEmpty(Settings.Domain))
                {
                    Cookie.Domain = Settings.Domain;
                }
                Cookie.Expires = DateTime.Now.AddDays(-1);
                System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
                return true;
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        /// 更新cookie过期时间
        /// </summary>
        /// <param name="cookieName"></param>
        /// <param name="cookieValue"></param>
        /// <param name="minutes"></param>
        public static void ModCookies(string cookieName, string cookieValue, int minutes)
        {
            var httpCookie = HttpContext.Current.Response.Cookies[cookieName];
            if (httpCookie != null)
            {
                httpCookie.Value = cookieValue;
                httpCookie.Expires = DateTime.Now.AddMinutes(minutes);
            }
        }
    }

 

posted @ 2021-10-13 11:00  清语堂  阅读(166)  评论(0编辑  收藏  举报