界面:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!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>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Image ID="Image1" runat="server" ImageUrl="YZM.aspx" />
<asp:Button ID="Button1" runat="server" Text="验证" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
<script type="text/javascript">
var a = ;
//点击图片更换验证码
document.getElementById("Image1").onclick = function () {
this.setAttribute("src", "yzm.aspx?id=" + a);
a++;
}
</script>
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button1.Click += Button1_Click;
} void Button1_Click(object sender, EventArgs e)
{
string t1 = TextBox1.Text;
string t2 = Session["YZM"].ToString(); if (t1.ToUpper() == t2.ToUpper())
{
Label1.Text = "验证成功!";
}
else
{
Label1.Text = "验证失败!";
} }
}
验证码制作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing; public partial class YZM : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Bitmap img = new Bitmap(, );//验证码图片大小
Graphics g = Graphics.FromImage(img);
Random r = new Random();
//背景色
List<Color> clist = new List<Color>();
clist.Add(Color.Yellow);
clist.Add(Color.Green);
clist.Add(Color.Blue);
clist.Add(Color.Pink);
clist.Add(Color.Orange);
clist.Add(Color.AliceBlue);
clist.Add(Color.Aqua);
clist.Add(Color.Cyan);
clist.Add(Color.DarkOliveGreen);
clist.Add(Color.Black); g.FillRectangle(new SolidBrush(clist[r.Next(, clist.Count)]), , , , ); for (int i = ; i < ; i++)
{
Color ccc = clist[r.Next(, clist.Count)];//随机颜色 Pen ppp = new Pen(new SolidBrush(ccc), r.Next(, ));//随机线条 g.DrawLine(ppp, new PointF(r.Next(, ), r.Next(, )), new PointF(r.Next(, ), r.Next(, )));
} //验证码
string all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string s = ""; for (int i = ; i < ; i++)
{
int a = r.Next(all.Length);//随机取数
s += all.Substring(a, );
} Session["YZM"] = s; g.DrawString(s, new Font("微软雅黑", ), new SolidBrush(Color.Red), new PointF(, )); img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
Response.End(); }
}