目录
效果图:
aspx源:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.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>
<img src="validate.jpg?" style="width: 100px; height: 34px;cursor:pointer" onclick="this.src=this.src+'a'"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
aspx后端部分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text==Session["CheckCode"].ToString())
{
Response.Write("正确");
}
}
}
}
ValidateCode.cs文件:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.SessionState;
namespace WebApplication3
{
//验证码
public class ValidateCode : IHttpHandler, IRequiresSessionState
{
/// <summary>
/// 验证码类型(0-字母数字混合,1-数字,2-字母)
/// </summary>
private string validateCodeType = "0";
/// <summary>
/// 验证码字符个数
/// </summary>
private int validateCodeCount = 4;
/// <summary>
/// 验证码的字符集,去掉了一些容易混淆的字符
/// </summary>
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
public void ProcessRequest(HttpContext context)
{
context.Response.BufferOutput = true;
context.Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
context.Response.AppendHeader("Pragma", "No-Cache");
//获取设置参数
if (!string.IsNullOrEmpty(context.Request.QueryString["validateCodeType"]))
{
validateCodeType = context.Request.QueryString["validateCodeType"];
}
if (!string.IsNullOrEmpty(context.Request.QueryString["validateCodeCount"]))
{
int.TryParse(context.Request.QueryString["validateCodeCount"], out validateCodeCount);
}
//生成验证码
this.CreateCheckCodeImage(GenerateCheckCode(context), context);
}
private string GenerateCheckCode(HttpContext context)
{
char code;
string checkCode = String.Empty;
Random random = new Random();
for (int i = 0; i < validateCodeCount; i++)
{
code = character[random.Next(character.Length)];
// 要求全为数字或字母
if (validateCodeType == "1")
{
if ((int)code < 48 || (int)code > 57)
{
i--;
continue;
}
}
else if (validateCodeType == "2")
{
if ((int)code < 65 || (int)code > 90)
{
i--;
continue;
}
}
checkCode += code;
}
context.Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
context.Session.Add("CheckCode", checkCode);
return checkCode;
}
private void CreateCheckCodeImage(string checkCode, HttpContext context)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 15.0 + 40)), 23);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
int cySpace = 16;
for (int i = 0; i < validateCodeCount; i++)
{
g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
}
//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}