验证码可以防止恶意破解密码、刷票、刷页等恶意的网络行为
是加强网站安全的必备技术,是重要的验证方法之一。
1.创建一个网站,并在网站中添加HttpHandler类,继承IhttpHandler与IRequiresSessionState接口,编写相关代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace WebApplication1
{
public class HttpHandler : IHttpHandler, IRequiresSessionState
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
//定义一个随机对象
Random random = new Random();
//生成随机数
string word = "123456789QWEASDZXCVBNFGH";
string code = null;
for(int i = 0; i < 6; i++)
{
code += word[random.Next(0, word.Length)];
}
//将验证码放到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.Pink, new Point(2, 2));
graphics.Flush();
bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
2.添加一个web窗体,使用验证码实现登录验证功能。页面如下图:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width:100%;" border="1" >
<tr>
<td>账号:</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" style="margin-left: 0px" Width="139px"></asp:TextBox>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>验证码:</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Image ID="Image1" runat="server" ImageUrl="~/image/2.jpg" Width="200px" Height="200px"/>
<asp:LinkButton ID="LinkButton1" runat="server">刷新</asp:LinkButton>
</td>
</tr>
</table>
<asp:Button ID="Button1" runat="server" Text="提交" />
</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
3.后台的部分代码如下:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string account = TextBox1.Text;
string password = TextBox2.Text;
string code = TextBox3.Text;
if(code != "")
{
if (Session["vcode"].ToString() == code.ToLower())
{
if (account == "梁坤" && password == "38438")
{
Response.Redirect("WebForm1.aspx");
}
else
{
Label1.Text = "账号或者密码不正确";
}
}
else
{
Label1.Text = "验证码不正确";
}
}
}
}
}
4.访问页面,等待结果
感谢观看。