登录退出代码

1.登录代码

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="userNo"></param>
        /// <param name="password"></param>
        /// <param name="persistCookie"></param>
        /// <returns></returns>
        public static KeyValuePair<bool, string> Login(string userNo, string password, bool persistCookie = false)
        {
            if (HttpContext.Current == null) return new KeyValuePair<bool, string>(false, "请求异常!");
            password = Com.Encrypt(password, key);//密码加密了两次,这里是第一次

            //这边需要验证账户密码是否正确,正确之后,才写入cookie
            
            User su = GetUser(userNo);
            HttpContext.Current.Session["CurrentUser"] = su;
            //如果勾选了记住我,则写入cookie
            if (persistCookie)
            {
                string eUser = Com.Encrypt("User", key);
                string eUserNo = Com.Encrypt("UserNo", key);
                string ePassword = Com.Encrypt("Password", key);
                string eNo = Com.Encrypt(userNo, key);
                string ePw = Com.Encrypt(password, key);//密码再加密一次
                HttpCookie Cookie = HttpContext.Current.Request.Cookies[eUser];
                if (Cookie == null || !Cookie.Values[eUserNo].Equals(eNo))
                {
                    Cookie = new HttpCookie(eUser);
                    Cookie.Values.Add(eUserNo, eNo);//将账号写入cookie
                    Cookie.Values.Add(ePassword, ePw);//将密码写入cookie。。。这两个cookie的键  也是经过加密的
                    Cookie.Expires = DateTime.Now.AddDays(365);
                    HttpContext.Current.Response.Cookies.Add(Cookie);
                }
            }
            return new KeyValuePair<bool, string>(true, "");
        }

2.退出代码

无非就是获得之前写入的cookie,然后设置它的有效时间

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public static KeyValuePair<bool, string> Logout()
        {
            if (HttpContext.Current == null) return new KeyValuePair<bool, string>(false, "请求异常!");
            HttpContext.Current.Session["CurrentUser"] = null;
            HttpContext.Current.Session["Authenticated"] = null;
            string eUser = Com.Encrypt("User", key);
            string eUserNo = Com.Encrypt("UserNo", key);
            string ePassword = Com.Encrypt("Password", key);
            HttpCookie Cookie = HttpContext.Current.Request.Cookies[eUser];
            if (Cookie != null)
            {
                Cookie = new HttpCookie(eUser);
                Cookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(Cookie);
            }
            return new KeyValuePair<bool, string>(true, "");
        }

 

posted @ 2015-09-20 22:16  凌晨10点13分  阅读(611)  评论(0编辑  收藏  举报