两种MVC 验证码
1.单纯的验证码 可以验证
先在文件夹下建一个VerificationCode 类里面写:
public static byte[] GetCodeImage()
{
//生成随机验证码
//定义验证码字符库,0和1容易与字母o和i混淆,尽量不用
char[] codesSource = { '2', '3', '4', '5', '6', '7', '8', '9' };
int codesLength = 4; //验证码字符个数
char[] codes = new char[codesLength]; //验证码字符数组
Random rnd = new Random(); //定义一个随机数生成器
//生成随机验证码
for (int i = 0; i < codesLength; i++)
{
//从验证码字符库里随机取一个字符赋值给验证码的第i个字符
codes[i] = codesSource[rnd.Next(codesSource.Length)];
}
//将生成的验证码字符串赋值给Session对象
HttpContext.Current.Session["VerificationCode"] = string.Join("", codes);
//定义验证码图片对象
int charSize = 24; //验证码字符大小
int imgWidth = charSize * (codesLength + 1); //生成验证码图片的宽度
int imgHeight = charSize * 2; //生成验证码图片的高度
Bitmap bmp = new Bitmap(imgWidth, imgHeight);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
//在背景上添加噪线
for (int i = 0; i < 20; i++)
{
int x1 = rnd.Next(imgWidth), y1 = rnd.Next(imgHeight);
int x2 = rnd.Next(imgWidth), y2 = rnd.Next(imgHeight);
//随机线颜色随机,宽度在1和2值之间随机
Pen pen = new Pen(Color.FromArgb(rnd.Next()), rnd.Next(1, 3));
g.DrawLine(pen, x1, y1, x2, y2);
}
//添加验证码字符
Font font = new Font("黑体", charSize, FontStyle.Bold);
//定义一个渐变颜色的笔刷
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, charSize, charSize), Color.LightGreen, Color.Red, 1.5F);
for (int i = 0; i < codesLength; i++)
{
//重新定义一个位图对象和绘图对象,画随机旋转的单个字符
Bitmap bmp1 = new Bitmap(charSize * 3, charSize * 3);
Graphics g1 = Graphics.FromImage(bmp1);
Matrix matrix = new Matrix(); //定义一个矩阵对象来旋转字符
//沿参数中指定定随机旋转-30到30度之间的角度
matrix.RotateAt(rnd.Next(-30, 30), new Point(charSize / 2 - 4, charSize - 4));
g1.Transform = matrix;
//画单个字符,并把生成的图形画到验证码图形对象上
g1.DrawString(codes[i].ToString(), font, brush, 0, 0);
g.DrawImage(bmp1, charSize / 2 + charSize * i, (imgHeight - charSize) / 2);
g1.Dispose();
}
//在前景上添加噪点
for (int i = 0; i < 250; i++)
{
int x = rnd.Next(imgWidth), y = rnd.Next(imgHeight);
bmp.SetPixel(x, y, Color.FromArgb(rnd.Next()));
}
//画验证码的边框
g.DrawRectangle(new Pen(Color.Black), 0, 0, imgWidth - 1, imgHeight - 1);
//将图形对象写入内存流,并返回内存流的字节数组
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Jpeg);
g.Dispose(); bmp.Dispose();
return ms.ToArray();
}
然后在控制器中加入两个方法 注意只用给Index一个添加视图
public ActionResult Index()
{
return View();
}
//生成验证码图片
//返回验证码图形内容,提供给视图img控件显示
public FileResult GetVerificationCode()
{
return new FileContentResult(VerificationCode.GetCodeImage(), "image/jpeg");
}
//验证输入的验证码是否正确
//通过读取生成验证码时写入的Session对象的值与从视图中获取的输入值进行比较
public string CheckVerificationCode(string code)
{
string sessionCode = Session["VerificationCode"] == null ? "" : Session["VerificationCode"].ToString();
if (sessionCode == code)
return "验证码正确。";
else
return "验证码错误,请重新输入。";
}
主页面 也就是Index
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$("#img").click(function () {
//src属性值后加参数是为了避免浏览器的缓存机制
$(this).prop("src", "/Home/GetVerificationCode?t=" + new Date().getTime());
});
$("#btnCheck").click(function () {
$.ajax({
url: "/Home/CheckVerificationCode",
type: "post",
data: { code: $("#txtCode").val() }, //参数名code要和控制器CheckVerificationCode的参数名相同
success: function (data) {
alert(data);
$("#img").click(); //刷新验证码
}
});
});
});</script>
</head>
<body>
<input type="text" id="txtCode" />
<img src="/Home/GetVerificationCode" id="img" />
<input type="button" id="btnCheck" value="验证" />
</body>
</html>
2.在项目中使用
首先也是在文件夹下建一个VerificationCode 类里面写:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
namespace GT.Models
{
public class VerificationCode
{
public static byte[] GetCodeImage()
{
//生成随机验证码
//定义验证码字符库,0和1容易与字母o和i混淆,尽量不用
char[] codesSource = { '2', '3', '4', '5', '6', '7', '8', '9' };
int codesLength = 4; //验证码字符个数
char[] codes = new char[codesLength]; //验证码字符数组
Random rnd = new Random(); //定义一个随机数生成器
//生成随机验证码
for (int i = 0; i < codesLength; i++)
{
//从验证码字符库里随机取一个字符赋值给验证码的第i个字符
codes[i] = codesSource[rnd.Next(codesSource.Length)];
}
//将生成的验证码字符串赋值给Session对象
HttpContext.Current.Session["VerificationCode"] = string.Join("", codes);
//定义验证码图片对象
int charSize = 24; //验证码字符大小
int imgWidth = charSize * (codesLength + 1); //生成验证码图片的宽度
int imgHeight = charSize * 2; //生成验证码图片的高度
Bitmap bmp = new Bitmap(imgWidth, imgHeight);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
//在背景上添加噪线
for (int i = 0; i < 20; i++)
{
int x1 = rnd.Next(imgWidth), y1 = rnd.Next(imgHeight);
int x2 = rnd.Next(imgWidth), y2 = rnd.Next(imgHeight);
//随机线颜色随机,宽度在1和2值之间随机
Pen pen = new Pen(Color.FromArgb(rnd.Next()), rnd.Next(1, 3));
g.DrawLine(pen, x1, y1, x2, y2);
}
//添加验证码字符
Font font = new Font("黑体", charSize, FontStyle.Bold);
//定义一个渐变颜色的笔刷
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, charSize, charSize), Color.LightGreen, Color.Red, 1.5F);
for (int i = 0; i < codesLength; i++)
{
//重新定义一个位图对象和绘图对象,画随机旋转的单个字符
Bitmap bmp1 = new Bitmap(charSize * 3, charSize * 3);
Graphics g1 = Graphics.FromImage(bmp1);
Matrix matrix = new Matrix(); //定义一个矩阵对象来旋转字符
//沿参数中指定定随机旋转-30到30度之间的角度
matrix.RotateAt(rnd.Next(-30, 30), new Point(charSize / 2 - 4, charSize - 4));
g1.Transform = matrix;
//画单个字符,并把生成的图形画到验证码图形对象上
g1.DrawString(codes[i].ToString(), font, brush, 0, 0);
g.DrawImage(bmp1, charSize / 2 + charSize * i, (imgHeight - charSize) / 2);
g1.Dispose();
}
//在前景上添加噪点
for (int i = 0; i < 250; i++)
{
int x = rnd.Next(imgWidth), y = rnd.Next(imgHeight);
bmp.SetPixel(x, y, Color.FromArgb(rnd.Next()));
}
//画验证码的边框
g.DrawRectangle(new Pen(Color.Black), 0, 0, imgWidth - 1, imgHeight - 1);
//将图形对象写入内存流,并返回内存流的字节数组
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Jpeg);
g.Dispose(); bmp.Dispose();
return ms.ToArray();
}
}
}
然后控制器页面 顺便有注册的代码
public ActionResult YHZC()
{
return View();
}
[HttpPost]
public ActionResult YHZC(User pt,string lan,string yzan) {
if (yzan== Session["VerificationCode"].ToString())
{
//实例化
User p = new User();
p.Name = pt.Name;
p.Age = pt.Age;
if (lan == "0")
{
p.Sex = "男";
}
else
{
p.Sex = "女";
}
p.Sfz = pt.Sfz;
p.Sjh = pt.Sjh;
p.Jf = 0;
p.Ye = 0;
p.Zh = pt.Zh;
p.Mm = pt.Mm;
p.Hy = "普通";
dd.User.Add(p);
dd.SaveChanges();
return Content("<script>alert('注册成功');window.location.href='DLYM'; </script>");
}
else
{
return Content("<script>alert('验证码错误!!!');window.location.href='YHZC';</script>");
}
}
//验证码
//返回验证码图形内容,提供给视图img控件显示
public FileResult GetVerificationCode()
{
return new FileContentResult(VerificationCode.GetCodeImage(), "image/jpeg");
}
最后是视图
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>YHZC</title>
<link href="~/css/DL.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$("#img").click(function () {
//src属性值后加参数是为了避免浏览器的缓存机制
$(this).prop("src", "/DLZC/GetVerificationCode?t=" + new Date().getTime());
});
});
</script>
</head>
<body>
<form id="form1" action="YHZC" method="post">
<div class="login">
<div class="login-top">
<h1>欢乐购注册</h1>
<input id="Text1" type="text" placeholder="姓名" name="Name" required="required" />
<input id="Text1" type="text" placeholder="年龄" name="Age" required="required"/>
<input id="Text1" type="text" placeholder="身份证" name="Sfz" required="required"/>
<input id="Text1" type="text" placeholder="手机号" name="Sjh" required="required"/>
<input id="Text1" type="text" placeholder="账号" name="Zh" required="required"/>
<input id="Text1" type="text" placeholder="密码" name="Mm" required="required"/>
<div class="xban">
性别:
<input id="Radio1" type="radio" name="lan" value="0" checked="checked" />男
<input id="Radio1" type="radio" name="lan" value="1" />女
</div>
<div>
@*验证码*@
<input type="text" id="txtCode" style="width:50%;" name="yzan" required="required"/>
<img src="/DLZC/GetVerificationCode" id="img" />
</div>
<div class="forgot">
<a href="/DLZC/DLYM/">返回</a>
<input id="btnCheck" type="submit" value="确认" />
</div>
</div>
<div class="login-bottom">
<h3><a href="#">游客查看</a></h3>
</div>
</div>
<div class="copyright">
<p>Copyright © 2022.Company name All rights reserved.</p>
</div>
</form>
</body>
</html>