c#登录时保存账号密码到cookie

登陆界面有用户名、密码输入框,一个’记住账号密码‘的复选框。

1.登录时,勾选‘记住账号密码‘复选框,则会把用户名密码保存在客户端cookie里,保存时间为最大值(直到用户清除浏览器缓存或者取消勾选’记住账号密码‘复选框);

2.登录时,取消勾选‘记住账号密码‘复选框,会清除cookie保存的用户名密码。

3.登录时,当修改了用户名密码,会判断cookie保存的值是否与输入的相同,如果不同,则会修改cookie的值。

4.登录时,当勾选了‘记住账号密码‘复选框,下次打开登录界面,‘记住账号密码‘复选框初始化为选中状态(这样用户就明白用户名和密码已经保存在cookie中);否则,是未选中状态。(同QQ登录)

 

主要代码:

一、前端

html:

<body>
    <form name="form1" method="post">
        <label>用户名</label><input type="text" name="UserName" id="username" />
        <label>密 码</label><input type="password" name="Password" id="userpass" />
        <input type="button" onclick="f_Login()" name="sm1" class="login_btn" value="登录" />
        <input id="rd" type="checkbox" name="rd_S" style="margin: 20px 0px 2px 20px" />
        <label style="margin-top: 20px">记住账号密码</label>
    </form>
</body>
</html>

 

js、jquery:

<script type="text/javascript">
        var rootPath = '@Url.Content("~/Admin/")';
        var username = '@ViewBag.UserName';
        var password = '@ViewBag.UserPassWord';

        $(document).ready(function () {
            if (username != "") {
                $("#username").attr("value", username);
                $("#userpass").attr("value", password);
                $("#rd").attr("checked", "checked"); //当cookie记录了账号密码,则初始化‘记住账号密码’复选框时为勾选状态
            }
            else {
                $("#rd").removeAttr("checked");
            }
        });

       @*登录*@
        function f_Login() {
            var IsSaveLoInfo; //标识是否记住账号密码
            if ($("#rd").attr("checked")) {
                IsSaveLoInfo = true; 
            }
            LG.ajax({
                url: '@Url.Content("~/Admin/Login/LoginAndRedirect")',
                loading: '正在登陆中...',
                data: { UserName: $("#username").val(), Password: $("#userpass").val(), IsSaveLoInfo: IsSaveLoInfo },
                success: function (result) {
                    if (!result) {
                        LG.showError("登录失败,帐号或密码错误!");
                        return false;
                    }
                    location.href = "@Url.Content("~/Admin/Manage/Index")";
                },
                error: function (message) {
                    LG.showError(message);
                }
            });
        }
    </script>

 


二、后台:

[Description("加载登陆页面")]
 public ActionResult UserLogin()
  {
     //获取cookie保存的账号密码
     string UserNameCookie = CookieHelper.GetCookieValue("UserNameCookie");
     string UserPasswordCookie = CookieHelper.GetCookieValue("UserPasswordCookie");
     ViewBag.UserName = UserNameCookie;
     ViewBag.UserPassWord = UserPasswordCookie;
     return View("Login");
  }

 [Description("login登录,登录成功则跳转")]
  public ActionResult LoginAndRedirect()
   {
      UserRequest request = new UserRequest(HttpContext);
      bool IsSaveLoginInfo = Convert.ToBoolean(HttpContext.Request["IsSaveLoInfo"]); //是否保存登陆账号密码          
      string UserNameCookie = CookieHelper.GetCookieValue("UserNameCookie");
      string UserPasswordCookie = CookieHelper.GetCookieValue("UserPasswordCookie");
      //判断是否把登陆账号密码到cookie
      if (IsSaveLoginInfo) 
      {
        if(UserNameCookie != request.UserName )//当输入的用户名与cookie保存的不同,修改cookie的
           CookieHelper.SetCookie("UserNameCookie", request.UserName, DateTime.MaxValue);
        if(UserPasswordCookie != request.Password)
           CookieHelper.SetCookie("UserPasswordCookie", request.Password, DateTime.MaxValue);
      }
      else
      {
        CookieHelper.ClearCookie("UserNameCookie");
        CookieHelper.ClearCookie("UserNameCookie");
      }
     ………其他处理代码……… 
   }

 

 

CookieHelper类:

    /// <summary>
    /// Cookie类
    /// </summary>
    public class CookieHelper
    {
        /// <summary>
        /// 清除指定Cookie
        /// </summary>
        /// <param name="cookiename">cookiename</param>
        public static void ClearCookie(string cookiename)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddYears(-3);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }

        /// <summary>
        /// 获取指定Cookie值
        /// </summary>
        /// <param name="cookiename">cookiename</param>
        /// <returns></returns>
        public static string GetCookieValue(string cookiename)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
            string cookievalue = string.Empty;
            if (cookie != null)
            {
                cookievalue = cookie.Value;
            }
            return cookievalue ;
        }

        /// <summary>
        /// 添加一个Cookie
        /// </summary>
        /// <param name="cookiename">cookie名</param>
        /// <param name="cookievalue">cookie值</param>
        /// <param name="expires">过期时间 DateTime</param>
        public static void SetCookie(string cookiename, string cookievalue, DateTime expires)
        {        
            HttpCookie cookie = new HttpCookie(cookiename)
            {
                Value = cookievalue,
                Expires = expires
            };
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }

 

posted @ 2015-03-03 16:27  goodgirlmia  阅读(5738)  评论(0编辑  收藏  举报
作者:goodgirlmia 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。