ASP.Net - 使用Cookie/Session实现记住密码功能
核心代码如下:
public partial class Login : System.Web.UI.Page { UserInfo u = new UserInfo();//引用Model/BLL层,接下来需要查询数据库 UserInfoBLL bll = new UserInfoBLL(); public string ErrorMsg { get; set; }//定义错误消息 protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) //提交post请求,用户主动点击登录按钮 { if (CheckValidateCode())//1.判断验证码是否正确 { UserLoginIn();//2.判断用户名和密码是否正确 } else { ErrorMsg = "验证码错误"; } } else//Get请求,用户输入Url后回车或者刷新时 { CheckCookieInfo();//检验Cookie信息 } } //检查Cookie信息 private void CheckCookieInfo() { if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null)//存在Cookie信息 { string userID = Request.Cookies["cp1"].Value;//获取用户ID string userPwd = Request.Cookies["cp2"].Value;//获取密码 //判断Cookie中存储的用户名是否正确 u = bll.GetUserInfoByUserID(userID);//根据id获取用户对象 if (userPwd != MD5Helper.Md5(MD5Helper.Md5(u.UserPwd)))//检查密码是否相等 { ErrorMsg = "用户名密码错误"; Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1);//销毁Cookie Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1); } else { Session["userInfo"] = u;//将用户对象给Session Response.Redirect("AdminIndex.aspx");//跳转到管理主页,登录成功 } } } //判断验证码是否正确 private bool CheckValidateCode() { bool isSuccess = false; if (Session["code"] != null)//验证码生成时保存在Session中的Code信息 { string sysCode = Session["code"].ToString(); string txtCode = Request.Form["txtCode"];//获取用户输入的验证码信息 if (sysCode.Equals(txtCode, StringComparison.InvariantCultureIgnoreCase))//判断验证码是否匹配,忽略大小写 { //节约服务端内存 //安全 Session["code"] = null;//销毁Session信息 isSuccess = true; } } return isSuccess; } //判断用户名和密码是否正确 private void UserLoginIn() { string userID = Request.Form["txtClientID"].ToString(); string userPwd = Request.Form["txtPassword"].ToString(); u = bll.GetUserInfoByUserNameAndPassWord(userID, userPwd); if (u.UserID != userID) { ErrorMsg = "用户名密码错误";//这里不用提示的太过准确防止用户恶意撞库 } else { Session["userInfo"] = u;//将用户对象给Session //判断用户是否选中了“记住我” if (!string.IsNullOrEmpty(Request.Form["CheckMe"])) { HttpCookie cookie1 = new HttpCookie("cp1", userID); HttpCookie cookie2 = new HttpCookie("cp2", MD5Helper.Md5(MD5Helper.Md5(userPwd))); cookie1.Expires = DateTime.Now.AddDays(1); cookie2.Expires = DateTime.Now.AddDays(1); //将Cookie放在响应报文中发送给浏览器 Response.Cookies.Add(cookie1); Response.Cookies.Add(cookie2); } Response.Redirect("AdminIndex.aspx");//跳转到用户管理主页 } } }
验证码公共类:

1 using System; 2 using System.Collections.Generic; 3 using System.Drawing; 4 using System.Drawing.Drawing2D; 5 using System.Drawing.Imaging; 6 using System.IO; 7 using System.Linq; 8 using System.Text; 9 using System.Threading.Tasks; 10 using System.Web; 11 12 namespace TestProject.Common 13 { 14 public class ValidateCode 15 { 16 public ValidateCode() 17 { 18 } 19 /// <summary> 20 /// 验证码的最大长度 21 /// </summary> 22 public int MaxLength 23 { 24 get { return 10; } 25 } 26 /// <summary> 27 /// 验证码的最小长度 28 /// </summary> 29 public int MinLength 30 { 31 get { return 1; } 32 } 33 /// <summary> 34 /// 生成验证码 35 /// </summary> 36 /// <param name="length">指定验证码的长度</param> 37 /// <returns></returns> 38 public string CreateValidateCode(int length) 39 { 40 int[] randMembers = new int[length]; 41 int[] validateNums = new int[length]; 42 string validateNumberStr = ""; 43 //生成起始序列值 44 int seekSeek = unchecked((int)DateTime.Now.Ticks); 45 Random seekRand = new Random(seekSeek); 46 int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000); 47 int[] seeks = new int[length]; 48 for (int i = 0; i < length; i++) 49 { 50 beginSeek += 10000; 51 seeks[i] = beginSeek; 52 } 53 //生成随机数字 54 for (int i = 0; i < length; i++) 55 { 56 Random rand = new Random(seeks[i]); 57 int pownum = 1 * (int)Math.Pow(10, length); 58 randMembers[i] = rand.Next(pownum, Int32.MaxValue); 59 } 60 //抽取随机数字 61 for (int i = 0; i < length; i++) 62 { 63 string numStr = randMembers[i].ToString(); 64 int numLength = numStr.Length; 65 Random rand = new Random(); 66 int numPosition = rand.Next(0, numLength - 1); 67 validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); 68 } 69 //生成验证码 70 for (int i = 0; i < length; i++) 71 { 72 validateNumberStr += validateNums[i].ToString(); 73 } 74 return validateNumberStr; 75 } 76 77 /// <summary> 78 /// 创建验证码的图片 79 /// </summary> 80 /// <param name="containsPage">要输出到的page对象</param> 81 /// <param name="validateNum">验证码</param> 82 public void CreateValidateGraphic(string validateCode, HttpContext context) 83 { 84 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); 85 Graphics g = Graphics.FromImage(image); 86 try 87 { 88 //生成随机生成器 89 Random random = new Random(); 90 //清空图片背景色 91 g.Clear(Color.White); 92 //画图片的干扰线 93 for (int i = 0; i < 25; i++) 94 { 95 int x1 = random.Next(image.Width); 96 int x2 = random.Next(image.Width); 97 int y1 = random.Next(image.Height); 98 int y2 = random.Next(image.Height); 99 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 100 } 101 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); 102 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), 103 Color.Blue, Color.DarkRed, 1.2f, true); 104 g.DrawString(validateCode, font, brush, 3, 2); 105 //画图片的前景干扰点 106 for (int i = 0; i < 100; i++) 107 { 108 int x = random.Next(image.Width); 109 int y = random.Next(image.Height); 110 image.SetPixel(x, y, Color.FromArgb(random.Next())); 111 } 112 //画图片的边框线 113 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 114 //保存图片数据 115 MemoryStream stream = new MemoryStream(); 116 image.Save(stream, ImageFormat.Jpeg); 117 //输出图片流 118 context.Response.Clear(); 119 context.Response.ContentType = "image/jpeg"; 120 context.Response.BinaryWrite(stream.ToArray()); 121 } 122 finally 123 { 124 g.Dispose(); 125 image.Dispose(); 126 } 127 } 128 /// <summary> 129 /// 得到验证码图片的长度 130 /// </summary> 131 /// <param name="validateNumLength">验证码的长度</param> 132 /// <returns></returns> 133 public static int GetImageWidth(int validateNumLength) 134 { 135 return (int)(validateNumLength * 12.0); 136 } 137 /// <summary> 138 /// 得到验证码的高度 139 /// </summary> 140 /// <returns></returns> 141 public static double GetImageHeight() 142 { 143 return 22.5; 144 } 145 } 146 }
作者:Jeremy.Wu
出处:https://www.cnblogs.com/jeremywucnblog/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。