C#方式操作Cookie

  1、设置cookie

     public static void SetCookie(string TokenValue)
        {
            HttpCookie tokencookie = new HttpCookie("localtoken");
            tokencookie.Value = TokenValue;
       //tokencookie.Values.Set("UserID", user.Key);
            var domain = WebConfigHelper.GetWebConfigValue("CookiesDomain");
            if (!string.IsNullOrWhiteSpace(domain))
            {
                tokencookie.Domain = domain;
            }
            HttpContext.Current.Response.Cookies.Add(tokencookie);
            return;
        }

  2、读取cookie   

        public static string GetCookie()
        {
            var cookie = HttpContext.Current.Request.Cookies["localtoken"];
            if (cookie != null)
                return cookie.Value;
            return string.Empty;
        }

  3、移出cookie,就是设置cookie过期

        public static void RemoveToken(string UserName)
        {
            if (TokenStore != "cookies")
                RedisHelper.Remove(ssoPrefix + UserName);

            var cookie = HttpContext.Current.Request.Cookies["localtoken"];
            if (cookie != null)
            {
                var domain = WebConfigHelper.GetWebConfigValue("CookiesDomain");
                if (!string.IsNullOrWhiteSpace(domain))
                {
                    cookie.Domain = domain;
                }
                cookie.Expires = DateTime.Now.AddDays(-1);
            }
            return;
        }

 

posted @ 2016-04-24 10:41  寂寞之砂  阅读(634)  评论(0编辑  收藏  举报