在网页中登录窗口是最常见的,如果把登录信息存在客户机Cookie中,下次用户登录时,网页先在客户机上查找登录信息,如果成功即可跳过登录步骤直接到主窗口,如登录界面如下:
实现:
1、第一次登录时保存到Cookie中,我使用的是ActionResult:
public ActionResult Login(User user) { if (string.IsNullOrEmpty(user.Name) || string.IsNullOrEmpty(user.Pwd)) { return Content("no:请输入完整,不能为空!"); } User dbuser = dao.GetUserByName(user); if (dbuser == null) { return Content("no:用户名错误!"); } if (dbuser.Pwd != user.Pwd) { return Content("no:密码错误!"); } var record = Request["ckbrecord"].ToBoolean(); SetCookie(record,user); Session["userinfo"] = dbuser; return Content("ok:"+dbuser.Rank); }
//设置cookie; private void SetCookie(bool record, User user) { if (record) { HttpCookie cookiename = new HttpCookie("printName", DES.MD5Encrypt(HttpUtility.UrlEncode(user.Name))); cookiename.Expires = DateTime.MaxValue; Response.Cookies.Add(cookiename); HttpCookie cookiepwd = new HttpCookie("printPwd", DES.MD5Encrypt(HttpUtility.UrlEncode(user.Pwd))); cookiepwd.Expires = DateTime.MaxValue; Response.Cookies.Add(cookiepwd); } else { HttpCookie cookiepwd = Request.Cookies["printPwd"]; if (cookiepwd != null) { cookiepwd.Expires = DateTime.Now.AddHours(-1); Response.Cookies.Add(cookiepwd); } } }
2、登录界面前检查Cookie,把下面判断放在首页Action中
//cookie登录 private User CookieLogin() { HttpCookie printName = Request.Cookies["printName"]; HttpCookie printPwd = Request.Cookies["printPwd"]; User user = new User(); if (printName != null && printPwd != null) { user.Name =HttpUtility.UrlDecode(DES.MD5Decrypt(printName.Value)); user.Pwd = HttpUtility.UrlDecode(DES.MD5Decrypt(printPwd.Value)); } return user; }
HttpUtility.UrlDecode和HttpUtility.UrlEncode是处理中文乱码问题用的。