zoukankan      html  css  js  c++  java
  • (转)asp.net 使用cookie完成记住密码自动登录

     代码如下 复制代码


            string username = this.txtUserName.Text;//用户名
            string password = this.txtPassword.Text;//密码

            if (UserManager.LoginValidate(username, password) && this.ckState.Checked == true)//判断登录名和密码是否正确和是否选择了记住用户名和密码的复选框
            {
               //判断客户端浏览器是否存在该Cookie 存在就先清除

                if (Request.Cookies["username"] != null && Request.Cookies["password"] != null)
                {
                    Response.Cookies["username"].Expires = System.DateTime.Now.AddSeconds(-1);//Expires过期时间
                    Response.Cookies["password"].Expires = System.DateTime.Now.AddSeconds(-1);
                }
                else
                {
                     //向客户端浏览器加入Cookie (用户名和密码 最好是使用MD5加密)
                    HttpCookie hcUserName1 = new HttpCookie("username");
                    hcUserName1.Expires = System.DateTime.Now.AddDays(7);
                    hcUserName1.Value = username;
                    HttpCookie hcPassword1 = new HttpCookie("password");
                    hcPassword1.Expires = System.DateTime.Now.AddDays(7);
                    hcPassword1.Value = password;
                    Response.Cookies.Add(hcUserName1);
                    Response.Cookies.Add(hcPassword1);
                }
    }

     //------------------------转到登录后的页面(有母板页写母板页最好)------------------------

     代码如下 复制代码
                  if (Request.Cookies["username"] != null && Request.Cookies["password"] != null)
                    {
                        //用户曾登录 
                     
                        username = Request.Cookies["username"].Value.ToString();  //读取Cookie 
                        password = Request.Cookies["password"].Value.ToString();//判断Cookie读取出来的用户名和密码是否能正确登录
                        if (UserManager.LoginValidate(username, password))
                        {
                          //登录后的代码
                 }         }

    //-------------------------------Cookie退出(加一个退出按钮)-------------------------------

    //退出  

     代码如下 复制代码
    HttpCookie hcUserName1 = new HttpCookie("username");   
    hcUserName1.Expires = System.DateTime.Now.AddDays(-7);   
    hcUserName1.Value = username;   
    HttpCookie hcPassword1 = new HttpCookie("password");   
    hcPassword1.Expires = System.DateTime.Now.AddDays(-7);   
    hcPassword1.Value = password;   
    Response.Cookies.Add(hcUserName1);   
    Response.Cookies.Add(hcPassword1);  
  • 相关阅读:
    SA练习题总结-篇一
    树上距离(树形DP)
    Codeforces Round #633(Div.2) E. Perfect Triples
    Codeforces Round #633 (Div. 2) D.Edge Weight Assignment
    问题 B: FZB(树形DP+边记忆化)
    【Matlab】自学笔记——基础知识篇
    【Python科学计算】Numpy——ndarry
    退役总结
    [树的遍历]树的遍历(PTA)
    [stl]集合相似度(PTA)
  • 原文地址:https://www.cnblogs.com/wanshutao/p/4286074.html
Copyright © 2011-2022 走看看