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

ASP.NET
如何在ASP.NET中使用SmtpMail发送邮件
在VB.NET中利用Split和Replace函数计算字数
Attribute应用:简化ANF自定义控件初始化过程
ASP.NET 2.0移动开发入门之使用样式
ASP.NET 2.0中使用OWC生成图表
ASP.NET 2.0中控件的简单异步回调
一个无法捕获ADO.NET Dataset的内存错误
深入解读ADO.NET2.0的十大最新特性
.Net平台下的分布式缓存设计
ASP.NET全局异常处理浅析
ASP.NET 2.0中文验证码的实现
浅析.NET平台编程语言的未来走向
.net 框架程序设计收藏
使用ASP.NET MVC Futures 中的异步Action
详解.NET中的XmlReader与XmlWriter
关于.NET中的Server push技术
asp.net页面执行机制
对比JSP和ASP.NET的存储过程
.NET 4.0不会包含System.Shell.CommandLine
ASP.NET十个有效性能优化的方法

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-23   浏览: 146 ::
收藏到网摘: 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() 获得验证码

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