1)新建一个web项目,并在web窗体中添加所需控件
下面是我的web窗体代码
<form id="form1" runat="server">
<div>
<p>验证码:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><asp:Image ID="Image1" runat="server" ImageUrl="images/3.jpg" Height="197px"/></p>//在image控件中随便加入一张图片当验证码背景板
<asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" ForeColor="Red"></asp:Label>
</div>
</form>
2)新建一个Handler类,并在其中编写验证码代码
以下是我的代码
public class Handler : IHttpHandler,IRequiresSessionState
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
//定义一个随机对象
Random random = new Random();
//生成随机数
string word = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM";//验证码所需要字符
string code = null;
for(int i = 0; i < 6; i++)
{
code += word[random.Next(0, word.Length)];//在word中随机抽取一个字符做验证码,共抽取六次
}
//将验证码放入session中
context.Session["code"] = code;
//定义画板
Bitmap bitmap = new Bitmap(100, 30);
Graphics graphics = Graphics.FromImage(bitmap);
//绘制验证码
graphics.DrawString(code,new Font("微软雅黑",12,FontStyle.Bold),Brushes.Red,new Point(5,5));
graphics.Flush();//将缓存区数据(验证码)放入输出流管道中
//将验证码输出到浏览器
bitmap.Save(context.Response.OutputStream,ImageFormat.Jpeg);
}
}
3)在web.config配置文件中的 configuration 中添加如下配置
<system.webServer>
<handlers>
<add name="code" verb="*" path="images/*.jpg" type="WebApplication1.Handler"/>
</handlers>
</system.webServer>
4)添加提交按钮的点击事件来判断验证码
以下是我的代码
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox3.Text != "")//验证非空
{
if (TextBox3.Text.ToUpper() == Session["code"].ToString())//验证验证码输入是否正确(ToUpper为将所输入的字符转为大写)
{
Label1.Text = "验证通过";
}
else
{
Label1.Text = "验证错误";
}
}
else
{
Label1.Text = "验证码不能为空";
}
}
以下是最终效果