最近自己写了一个自定义验证码控件把它拿出来和大家分享分享
具体步骤
1---》新建asp.net 网站
2---》添加新建项目 ,选择类库
3---》新建两个类
3.1--》自定义控件类(WebControl 派生类)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AuthCode
{
[ToolboxData("<{0}:AuthCode runat=server></{0}:AuthCode>")]
public class AuthCode : WebControl
{
/// <summary>
/// 获得验证码的值
/// </summary>
/// <returns>验证码</returns>
public string GetValue()
{
return HttpContext.Current.Session["value"].ToString();
}
[Bindable(true)]
[Category("Appearance")]
[Description("验证码字符长度")]
[DefaultValue("ss")]
[Localizable(true)]
//长度
internal static int mySize;
public int MySize
{
get { return AuthCode.mySize; }
set
{
AuthCode.mySize = value;
}
}
public AuthCode()
: base(HtmlTextWriterTag.Img)//重写父类的构造(输出流的HTML标记)
{ }
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);//将要输出的的HTML标签的属性和样式添加到指定的 HtmlTextWriter中
writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer");//添加样式
/**-
* 图片的onclick事件 "this.src='VerifyImg.jd?id='+Math.random()"
* 每次单击一次就有一个新的图片请求路径(VerifyImg.jd?id='+Math.random())参数只是
* 告诉浏览器这是一个新的请求然后经过 IHttpHander处理生成新的图片 id 没有任何实际意思(创造一个新的请求)
* -**/
writer.AddAttribute("onclick", "this.src='img.jd?id='+Math.random()");//添加js VerifyImg.jd
writer.AddAttribute(HtmlTextWriterAttribute.Src, "img.jd");
writer.AddAttribute("alt", "点击刷新");
}
}
}
3.2--》新建处理类(必须实现 IHttpHandler,IRequiresSessionState 两个接口)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web.SessionState;
using System.Drawing;
using System.IO;
namespace AuthCode
{
public class AuthCodeHttpHander:IHttpHandler,IRequiresSessionState
{
/// <summary>
/// 返回验证码字符
/// </summary>
/// <param name="codeCount">验证码长度</param>
/// <returns></returns>
private string GetRandomNumberString(int codeCount)
{
string strChoice = "2,3,4,5,6,7,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";
string[] strResult = strChoice.Split(new Char[] { ',' });
string strReturn = "";
Random rnd = new Random();
for (int i = 0; i < codeCount; i++)
{
int j = rnd.Next(strResult.Length);//随机数不能大于数组的长度
strReturn = strReturn + strResult[j].ToString();
}
return strReturn;
}
private Color GetColor()
{
return Color.Black;
}
private Bitmap CreateImage(string str_AuthCode)
{
/* -----------------------------绘制图片的样式 ------------------------------------*/
int width =str_AuthCode.Length* 21;
int height = 30;
Random rad = new Random();
Bitmap bmp = new Bitmap(width, height);
Graphics grp = Graphics.FromImage(bmp);// 在图片上绘制图形
grp.Clear(Color.YellowGreen);//填充bmp的背景色
grp.DrawRectangle(new Pen(Color.Red, 1), 0, 0, width - 1, height - 1);//绘制边框
int num = width * height;
for (int i = 0; i < num; i++)//在图片的指定坐标上画上有颜色的圆点
{
int x = rad.Next(width);
int y = rad.Next(height);
int r = rad.Next(255);
int g = rad.Next(255);
int b = rad.Next(255);
Color c = Color.FromArgb(r, g, b);
bmp.SetPixel(x, y, c);//在图片的指定坐标上画上有颜色的圆点
}
/*-------------------------- 在图片绘制字符串------------------------------------ */
Font f = new Font("宋体", 20, FontStyle.Bold);//定义字体
Brush br = new SolidBrush(Color.Black);//定义画笔的颜色 及字体的颜色
for (int i = 0; i < str_AuthCode.Length; i++)
{
string s = str_AuthCode.Substring(i, 1);//单个单个的将字画到图片上
Point p = new Point(i * 20 + rad.Next(3), rad.Next(3) + 1);//字体出现的位置(坐标)
grp.DrawString(s, f, br, p);//绘制字符串
}
grp.Dispose();
return bmp;//返回
}
/// <summary>
/// 是否可以处理远程的HTTP请求
/// </summary>
public bool IsReusable
{
get { return true; }
}
/// <summary>
/// 将验证码图片发送给WEB浏览器
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
int size = AuthCode.mySize; //Int32.Parse((String)context.Session["Size"]);
MemoryStream ms = new MemoryStream(); // 创建内存流(初始长度为0 自动扩充)
string NumStr = GetRandomNumberString(size);// 获得验证码字符
context.Session.Add("value", NumStr);//将验证码字符保存到session里面
Bitmap theBitmap = CreateImage(NumStr);// 获得验证码图片
theBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//将位图写入内存流
context.Response.ClearContent(); //清除缓冲区里的所有内容输出
context.Response.ContentType = "image/jpeg"; //需要输出图象信息 要修改HTTP头
context.Response.BinaryWrite(ms.ToArray()); //将内存流写入HTTP输出流
theBitmap.Dispose(); //释放资源
ms.Close();//释放资源
ms.Dispose();//释放资源
context.Response.End();
}
}
}
4---》生成解决方案和类库后打开Web窗体再工具栏可以看见
5--》拖放到web窗体
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AuthCode" namespace="AuthCode" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:AuthCode ID="AuthCode1" runat="server" MySize="5" />
</div>
</form>
</body>
</html>
设置验证码字符长度
6--》在webconfig文件添加节点
<system.web>
<httpHandlers>
<add verb="*" path="*.jd" type="AuthCode.AuthCodeHttpHander" />
</httpHandlers>
</system.web>
7--》在浏览器查看
点击可以刷新
8--》》this.AuthCode1.GetValue() 获得验证码
完
第一次写技术文章还请各位博友前辈多多指教