当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASp.Net自定义验证码控件

ASP.NET
ASP.NET开发:简化应用程序的开发支持Web标准
asp.net XMLHttpRequest实现用户注册前的验证
asp.net 页面间传值方法小结
asp.net url重写浅谈
asp.net 验证码生成和刷新及验证
C#精髓 GridView72大绝技 学习gridview的朋友必看
实例说明asp.net中的简单角色权限控制
asp.net网站开发包wq.dll打包下载
js与ASP.NET 中文乱码问题
asp.net checkbox 动态绑定id GridView删除提示
asp.net TextBox回车触发事件 图片在img显示
asp.net 脏字典过滤问题 用正则表达式来过滤脏数据
asp.NET 脏字过滤算法
asp.NET 脏字过滤算法 修改版
asp.net sql 数据库处理函数命令
asp.net Javascript 的几种写法与提示
ASP.NET MVC学习笔记
asp.net 中国身份证号码验证代码 非正则
Asp.net中使用Sqlite数据库的方法
asp.net 中文字符串提交乱码的解决方法

ASP.NET 中的 ASp.Net自定义验证码控件


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-23   浏览: 290 ::
收藏到网摘: n/a

最近自己写了一个自定义验证码控件把它拿出来和大家分享分享

具体步骤

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() 获得验证码

第一次写技术文章还请各位博友前辈多多指教