引文:众所周知,一般我们日常碰到的验证码是一个图形样式的,列入这个样子的,那么在这个图片里面我们想实现我们自己界面上有这样的一个验证码就需要做两个操作,一个是在我们自己界面上生成如图所示的一个验证码图片,第二个操作就是将验证码里面的字符和用户输入的字符对比。
首先我们来实现生成 生成验证码的这一部分,这时候我们需要封装一个类,里面有生成图片和字符的方法,其实本质上就是一个随机数,这个类卸载Model里面即可
public class CaptchaGenerator{string ocode;// 可选字符集合string letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";Random random = new Random();public string ConductOrginalcode() {for (int i = 0; i < 4; i++){ocode += letters[random.Next(letters.Length)];}return ocode;}public string GenerateCaptchaCode(){ return ocode;}public string GenerateCaptchaImage(){// 验证码图片的尺寸const int WIDTH = 60;const int HEIGHT = 30;// 创建Bitmap对象Bitmap bitmap = new Bitmap(WIDTH, HEIGHT);Graphics graphics = Graphics.FromImage(bitmap);graphics.Clear(Color.White);// 生成四位验证码string code ;code = ocode;// 绘制干扰线for (int i = 0; i < 20; i++){int x1 = random.Next(bitmap.Width);int y1 = random.Next(bitmap.Height);int x2 = random.Next(bitmap.Width);int y2 = random.Next(bitmap.Height);graphics.DrawLine(new Pen(Color.Coral), x1, y1, x2, y2);}// 绘制干扰点for (int i = 0; i < 200; i++){int x = random.Next(bitmap.Width);int y = random.Next(bitmap.Height);bitmap.SetPixel(x, y, Color.FromArgb(random.Next()));}// 绘制边框graphics.DrawRectangle(new Pen(Color.Black), new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));// 使用渐变画刷填充验证码文本LinearGradientBrush linearGradientBrush = new LinearGradientBrush(new Rectangle(0, 0, bitmap.Width, bitmap.Height), Color.Blue, Color.Green, 1.4f);graphics.DrawString(code, new Font("宋体", 20), linearGradientBrush, new PointF(0, 0));// 将Bitmap转换为MemoryStream,并进一步转换为Base64字符串MemoryStream ms = new MemoryStream();bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);byte[] imageBytes = ms.ToArray();ms.Close();string base64String = Convert.ToBase64String(imageBytes);return base64String;}}
这个类里面包含了三个方法第一个是生成随机数,第二个是生成字符的,第三个是根据字符来生成对应的图片
然后我们需要在我们需要的控制器里面调用这个类,用户比较的时候就拿第二个方法里面的字符去比较就可以了
// GET: GuestBookpublic ActionResult Index(int? page){// 生成验证码Session.Remove("CaptchaCode");CaptchaGenerator captchaGenerator = new CaptchaGenerator();captchaGenerator.ConductOrginalcode();string captchaBase64 = captchaGenerator.GenerateCaptchaImage();string captchaText = captchaGenerator.GenerateCaptchaCode();ViewBag.CaptchaImage = $"data:image/jpeg;base64,{captchaBase64}";Session["CaptchaCode"] = captchaText;int pageIndex = page ?? 2; // 新的初始页码int pageSize = 2; // 新的每页大小var guestBookQuery = from gb in db.GuestBooksorderby gb.AddDate descendingselect gb;/* Webdiyer.WebControls.Mvc.IPagedList<GuestBook> p1 = new Webdiyer.WebControls.Mvc.PagedList<GuestBook>(guestBookQuery.ToList(), pageIndex, pageSize);*/PagedList.IPagedList<GuestBook> p1 = guestBookQuery.ToPagedList(pageIndex, pageSize);return View(p1);}
然后需要的是在这个控制器里面我们还要写一个刷新验证码的方法,保证验证码错误和输入正确之后都要刷新一遍.
private void RefreshCaptcha(){Session.Remove("CaptchaCode");CaptchaGenerator captchaGenerator = new CaptchaGenerator();captchaGenerator.ConductOrginalcode();string captchaBase64 = captchaGenerator.GenerateCaptchaImage();string captchaText = captchaGenerator.GenerateCaptchaCode();ViewBag.CaptchaImage = $"data:image/jpeg;base64,{captchaBase64}";Session["CaptchaCode"] = captchaText;}
<tr><div style="display:flex;margin-left:10px;left:20%"><img src="@ViewBag.CaptchaImage" alt="验证码" /><input style="margin-left:13px" type="text" name="captcha" /></div></tr>
在视图里面添加这个关于验证码的
[HttpPost]public ActionResult Index(GuestBook guestBook,string captcha){if (Session["CaptchaCode"] != null && captcha != null){string captchaSessionValue = Session["CaptchaCode"] as string;if (captchaSessionValue == captcha){}else{return Content("<script>alert('验证码输入错误');window.location.href='/GuestBook/Index';</script>");}}RefreshCaptcha();int pageSize = 2;if (ModelState.IsValid){guestBook.AddDate = DateTime.Now;db.GuestBooks.Add(guestBook);db.SaveChanges();ModelState.Clear();}var guestBookQuery = from gb in db.GuestBooksorderby gb.AddDate descendingselect gb;PagedList.IPagedList<GuestBook> p1 = guestBookQuery.ToPagedList(1, pageSize);return View(p1);}
然后在表单验证的时候进行验证码和用户输入的字符进行比对即可