验证码html调用
验证码:<input name="txtCode0" type="text" id="txtCode0" class="login-text" size="" maxlength="">
<img src="CodeHandler.ashx" id="imgCode" alt="验证码" title="点击刷新验证码" align="middle"
style="height: 24px; width: 70px;" onclick="refreshRandCode()">
验证码刷新
//刷新验证码
function refreshRandCode() {
$('#imgCode').hide().attr('src',
'CodeHandler.ashx?' + Math.floor(Math.random() * 100)).fadeIn();
}
验证码后台判断
Session["checkCode"]
还有2个验证码效果请看我下一篇博客
验证码CodeHandler.ashx
难以分清的的字母i、o已删除
<%@ WebHandler Language="C#" Class="CodeHandler" %> using System;
using System.Web;
using System.Drawing; public class CodeHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState{ public string charSet = "0,1,2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
public void ProcessRequest (HttpContext context) {
string validateCode = CreateRandomCode();
context.Session["checkCode"] = validateCode;
CreateImage(validateCode, context);
} public bool IsReusable {
get {
return false;
}
} /// <summary>
/// 生成验证码
/// <param name="n">位数</param>
/// <returns>验证码字符串</returns>
private string CreateRandomCode(int n)
{
string[] CharArray = charSet.Split(',');
string randomCode = "";
int temp = -;
Random rand = new Random();
for (int i = ; i < n; i++)
{
if (temp != -)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
} int t = rand.Next(CharArray.Length - );
if (temp == t)
{
return CreateRandomCode(n);
} temp = t;
randomCode += CharArray[t];
}
return randomCode;
}
private void CreateImage(string checkCode, HttpContext context)
{
int iwidth = (int)(checkCode.Length * +);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, );
Graphics g = Graphics.FromImage(image);
Font f = new System.Drawing.Font("Arial", , (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold)); // 前景色
Brush b = new System.Drawing.SolidBrush(Color.Black); // 背景色
g.Clear(Color.White); // 填充文字
g.DrawString(checkCode, f, b, , ); // 随机线条
Pen linePen = new Pen(Color.Gray, );
Random rand = new Random();
for (int i = ; i < ; i++)
{
int x1 = rand.Next(image.Width);
int y1 = rand.Next(image.Height);
int x2 = rand.Next(image.Width);
int y2 = rand.Next(image.Height);
g.DrawLine(linePen, x1, y1, x2, y2);
} // 随机点
for (int i = ; i < ; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
image.SetPixel(x, y, Color.Gray);
} // 边框
g.DrawRectangle(new Pen(Color.Gray), , , image.Width - , image.Height - ); // 输出图片
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.ClearContent();
context.Response.ContentType = "image/Jpeg";
context.Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
} }
验证码效果: