登录页面的记住我功能
不能用session的原因:sessionID是以cookie的形式存在浏览器端的内存中 如果用户把浏览器关闭 则sessionID就消失
但是服务器端的session在过期时间内还是存在的 等到浏览器在 默认的过期时间内(20分钟)不在向服务器发送请求 则过了20分钟 session销毁!
前端简单模拟:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="RememberMe.Login" %> 2 3 4 5 6 7 842 439 16 17 18
后台代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 8 namespace RememberMe 9 {10 public partial class Login : System.Web.UI.Page11 {12 protected string uName;13 protected string pwd;14 protected void Page_Load(object sender, EventArgs e)15 {16 17 if (Request.Cookies["user"] != null)18 {19 uName = Request.Cookies["user"].Values["n"];20 pwd = Request.Cookies["user"].Values["p"];21 }22 if (IsPostBack)23 {24 string userName = Request.Form["txtName"];25 string userPwd = Request.Form["txtPwd"];26 if (!string.IsNullOrEmpty(Request.Form["rememberMe"]))27 {28 if (userName == "admin" && userPwd == "admin")29 {30 AlertAndRedirect("Index.aspx?n=" + userName, "登录成功");31 HttpCookie cookie = new HttpCookie("user");32 cookie["n"] = userName;33 cookie["p"] = userPwd;34 cookie.Expires = DateTime.Now.AddDays(7);35 Response.Cookies.Add(cookie);36 }37 else38 {39 AlertAndRedirect("Login.aspx", "登录失败");40 Response.Cookies["user"].Expires = DateTime.Now.AddDays(-1);41 }42 }43 else44 {45 Response.Cookies["user"].Expires = DateTime.Now.AddDays(-1);46 if (userName == "admin" && userPwd == "admin")47 {48 AlertAndRedirect("Index.aspx?n=" + userName, "登录成功");49 }50 else51 {52 AlertAndRedirect("Login.aspx", "登录失败");53 }54 }55 }56 57 }58 private void AlertAndRedirect(string redirectURL, string msg)59 {60 Response.Write("");61 }62 }63 }