asp.net的验证码控件(收藏) 作者:杲頔
作者:杲頔 文章地址
 using System;
using System;
 using System.Collections.Generic;
using System.Collections.Generic;
 using System.Text;
using System.Text;

 using System.Web;
using System.Web;
 using System.Drawing;
using System.Drawing;
 using System.IO;
using System.IO;
 using System.Web.SessionState;
using System.Web.SessionState;

 namespace jdTools.Web
namespace jdTools.Web
 {
{
 public class VerifyImageHttpHandle : IHttpHandler, IRequiresSessionState
    public class VerifyImageHttpHandle : IHttpHandler, IRequiresSessionState
 {
    {
 private string GetRandomNumberString(int codeCount)
        private string GetRandomNumberString(int codeCount)
 {
        {
 int j1;
            int j1;
 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 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[] strResult = strChoice.Split(new Char[] { ',' });
 string strReturn = "";
            string strReturn = "";
 Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
            Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
 for (int i = 0; i < codeCount; i++)
            for (int i = 0; i < codeCount; i++)
 {
            {
 Random rnd1 = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks));
                Random rnd1 = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks));
 j1 = rnd1.Next(strResult.Length);
                j1 = rnd1.Next(strResult.Length);
 rnd = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks));
                rnd = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks));
 strReturn = strReturn + strResult[j1].ToString();
                strReturn = strReturn + strResult[j1].ToString();
 }
            }
 return strReturn;
            return strReturn;  
 }
        }
 private Color GetColor()
        private Color GetColor()
 {
        {
 return Color.Black;
            return Color.Black;
 }
        }
 private Bitmap CreateImage(string str_ValidateCode)
        private Bitmap CreateImage(string str_ValidateCode)
 {
        {
 Random newRandom = new Random((int)DateTime.Now.Ticks);
            Random newRandom = new Random((int)DateTime.Now.Ticks);
 int int_ImageWidth = str_ValidateCode.Length * 14;
            int int_ImageWidth = str_ValidateCode.Length * 14;
 int int_ImageHeight = 20;
            int int_ImageHeight = 20;
 //  图高20px
            //  图高20px
 Bitmap theBitmap = new Bitmap(int_ImageWidth, int_ImageHeight);
            Bitmap theBitmap = new Bitmap(int_ImageWidth, int_ImageHeight);
 Graphics theGraphics = Graphics.FromImage(theBitmap);
            Graphics theGraphics = Graphics.FromImage(theBitmap);
 //  白色背景
            //  白色背景
 theGraphics.Clear(Color.White);
            theGraphics.Clear(Color.White);
 //  灰色边框
            //  灰色边框
 theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, int_ImageHeight);
            theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, int_ImageHeight);

 int num = theBitmap.Width * theBitmap.Height * 30 / 100;
            int num = theBitmap.Width * theBitmap.Height * 30 / 100;
 for (int iCount = 0; iCount < num; iCount++)
            for (int iCount = 0; iCount < num; iCount++)
 {
            {
 // 在随机的位置使用随机的颜色设置图片的像素
                // 在随机的位置使用随机的颜色设置图片的像素
 int x = newRandom.Next(theBitmap.Width);
                int x = newRandom.Next(theBitmap.Width);
 int y = newRandom.Next(theBitmap.Height);
                int y = newRandom.Next(theBitmap.Height);
 int r = newRandom.Next(255);
                int r = newRandom.Next(255);
 int g = newRandom.Next(255);
                int g = newRandom.Next(255);
 int b = newRandom.Next(255);
                int b = newRandom.Next(255);
 Color c = Color.FromArgb(r, g, b);
                Color c = Color.FromArgb(r, g, b);
 theBitmap.SetPixel(x, y, c);
                theBitmap.SetPixel(x, y, c);
 }//for
            }//for


 //  10pt的字体
            //  10pt的字体
 Font theFont = new Font("Arial", 12, FontStyle.Bold);
            Font theFont = new Font("Arial", 12, FontStyle.Bold);

 for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
            for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
 {
            {
 string str_char = str_ValidateCode.Substring(int_index, 1);
                string str_char = str_ValidateCode.Substring(int_index, 1);
 Brush newBrush = new SolidBrush(GetColor());
                Brush newBrush = new SolidBrush(GetColor());
 Point thePos = new Point(int_index * 13 + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
                Point thePos = new Point(int_index * 13 + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
 theGraphics.DrawString(str_char, theFont, newBrush, thePos);
                theGraphics.DrawString(str_char, theFont, newBrush, thePos);
 }
            }
 
            
 theGraphics.Dispose();
            theGraphics.Dispose();
 return theBitmap;
            return theBitmap;
 
            
 }
        }

 IHttpHandler 成员
        IHttpHandler 成员
 }
    }
 }
GetRandomNumberString方法用于生成指定个数的随机数字符串。
}
GetRandomNumberString方法用于生成指定个数的随机数字符串。
IHttpHandle接口的ProcessRequest方法可以启用 HTTP Web 请求的处理。
类VerifyImageHttpHandle 继承了IHttpHandle接口用于自定义程序处理的Web请求。然后在web.config的<system.web>节中配置
 <httpHandlers>
      <httpHandlers>
 <add verb="*" path="VerifyImg.jd" type="jdTools.Web.VerifyImageHttpHandle"/>
        <add verb="*" path="VerifyImg.jd" type="jdTools.Web.VerifyImageHttpHandle"/>
 </httpHandlers>
      </httpHandlers>
此时在浏览器中访问VerifyImg.jd时就会得到一个验证码图片,生成验证码的内容就完成了。
现在我们要自定义一个WEB自定义控件。其代码如下:
 using System;
using System;
 using System.Collections.Generic;
using System.Collections.Generic;
 using System.ComponentModel;
using System.ComponentModel;
 using System.Text;
using System.Text;
 using System.Web;
using System.Web;
 using System.Web.UI;
using System.Web.UI;
 using System.Web.UI.WebControls;
using System.Web.UI.WebControls;


 namespace jdTools.Web.UI
namespace jdTools.Web.UI
 {
{
 [ToolboxData("<{0}:VerifyImage runat=server></{0}:VerifyImage>")]
    [ToolboxData("<{0}:VerifyImage runat=server></{0}:VerifyImage>")]
 public class VerifyImage : WebControl
    public class VerifyImage : WebControl
 {
    {
 public string Value
        public string Value
 {
        {
 get { return HttpContext.Current.Session["Verify"].ToString(); }
            get { return HttpContext.Current.Session["Verify"].ToString(); }
 }
        }
 public virtual ImageAlign ImageAlign
        public virtual ImageAlign ImageAlign
 {
        {
 get
            get
 {
            {
 object obj2 = this.ViewState["ImageAlign"];
                object obj2 = this.ViewState["ImageAlign"];
 if (obj2 != null)
                if (obj2 != null)
 {
                {
 return (ImageAlign)obj2;
                    return (ImageAlign)obj2;
 }
                }
 return ImageAlign.NotSet;
                return ImageAlign.NotSet;
 }
            }
 set
            set
 {
            {
 if ((value < ImageAlign.NotSet) || (value > ImageAlign.TextTop))
                if ((value < ImageAlign.NotSet) || (value > ImageAlign.TextTop))
 {
                {
 throw new ArgumentOutOfRangeException("value");
                    throw new ArgumentOutOfRangeException("value");
 }
                }
 this.ViewState["ImageAlign"] = value;
                this.ViewState["ImageAlign"] = value;
 }
            }

 }
        }

 public VerifyImage()
        public VerifyImage()
 : base(HtmlTextWriterTag.Img)
            : base(HtmlTextWriterTag.Img)
 { }
        { }
 protected override void AddAttributesToRender(HtmlTextWriter writer)
        protected override void AddAttributesToRender(HtmlTextWriter writer)
 {
        {
 base.AddAttributesToRender(writer);
            base.AddAttributesToRender(writer);
 writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer");
 writer.AddAttribute("onclick", "this.src='VerifyImg.jd?id='+Math.random()", true);
            writer.AddAttribute("onclick", "this.src='VerifyImg.jd?id='+Math.random()", true);
 writer.AddAttribute(HtmlTextWriterAttribute.Src, "VerifyImg.jd");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, "VerifyImg.jd");
 string str2;
            string str2;
 switch (this.ImageAlign)
            switch (this.ImageAlign)
 {
            {
 case ImageAlign.Left:
                case ImageAlign.Left:
 str2 = "left";
                    str2 = "left";
 break;
                    break;

 case ImageAlign.Right:
                case ImageAlign.Right:
 str2 = "right";
                    str2 = "right";
 break;
                    break;

 case ImageAlign.Baseline:
                case ImageAlign.Baseline:
 str2 = "baseline";
                    str2 = "baseline";
 break;
                    break;

 case ImageAlign.Top:
                case ImageAlign.Top:
 str2 = "top";
                    str2 = "top";
 break;
                    break;

 case ImageAlign.Middle:
                case ImageAlign.Middle:
 str2 = "middle";
                    str2 = "middle";
 break;
                    break;

 case ImageAlign.Bottom:
                case ImageAlign.Bottom:
 str2 = "bottom";
                    str2 = "bottom";
 break;
                    break;

 case ImageAlign.AbsBottom:
                case ImageAlign.AbsBottom:
 str2 = "absbottom";
                    str2 = "absbottom";
 break;
                    break;

 case ImageAlign.AbsMiddle:
                case ImageAlign.AbsMiddle:
 str2 = "absmiddle";
                    str2 = "absmiddle";
 break;
                    break;

 case ImageAlign.NotSet:
                case ImageAlign.NotSet:
 str2="";
                    str2="";
 break;
                    break;
 default:
                default:
 str2 = "texttop";
                    str2 = "texttop";
 break;
                    break;
 }
            }
 if (str2 != "")
            if (str2 != "")
 writer.AddAttribute(HtmlTextWriterAttribute.Align, str2);
                writer.AddAttribute(HtmlTextWriterAttribute.Align, str2);
 }
        }
 }
    }
 }
}
 
VerifyImage 类定义了两个属性。其中Value属性用于取得session中存放的验证码的值。
这里就很简单了,没有必要详说。
在使用的时候aspx页面如下:
 <ul>
                    <ul>
 <li>用户名:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></li>
                        <li>用户名:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></li>
 <li>密 码:<asp:TextBox ID="txtPassWord" runat="server"></asp:TextBox></li>
                        <li>密 码:<asp:TextBox ID="txtPassWord" runat="server"></asp:TextBox></li>
 <li>检证码:<asp:TextBox ID="txtVerify" runat="server" Width="50px"></asp:TextBox><jd:VerifyImage ID="verify" runat="server" Height="23px" ImageAlign="AbsMiddle"/></li>
                        <li>检证码:<asp:TextBox ID="txtVerify" runat="server" Width="50px"></asp:TextBox><jd:VerifyImage ID="verify" runat="server" Height="23px" ImageAlign="AbsMiddle"/></li>
 </ul>
                    </ul>
aspx.cs中:
 if (txtVerify.Text != verify.Value)
            if (txtVerify.Text != verify.Value)
 {
            {
 //
                // .验证码错误
.验证码错误
 }
            }
 else
            else
 {
            {
 //
                // 验证码正确
验证码正确
 }
            }
 using System;
using System; using System.Collections.Generic;
using System.Collections.Generic; using System.Text;
using System.Text;
 using System.Web;
using System.Web; using System.Drawing;
using System.Drawing; using System.IO;
using System.IO; using System.Web.SessionState;
using System.Web.SessionState;
 namespace jdTools.Web
namespace jdTools.Web {
{ public class VerifyImageHttpHandle : IHttpHandler, IRequiresSessionState
    public class VerifyImageHttpHandle : IHttpHandler, IRequiresSessionState {
    { private string GetRandomNumberString(int codeCount)
        private string GetRandomNumberString(int codeCount) {
        { int j1;
            int j1; 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 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[] strResult = strChoice.Split(new Char[] { ',' }); string strReturn = "";
            string strReturn = ""; Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
            Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < codeCount; i++)
            for (int i = 0; i < codeCount; i++) {
            { Random rnd1 = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks));
                Random rnd1 = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks)); j1 = rnd1.Next(strResult.Length);
                j1 = rnd1.Next(strResult.Length); rnd = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks));
                rnd = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks)); strReturn = strReturn + strResult[j1].ToString();
                strReturn = strReturn + strResult[j1].ToString(); }
            } return strReturn;
            return strReturn;   }
        } private Color GetColor()
        private Color GetColor() {
        { return Color.Black;
            return Color.Black; }
        } private Bitmap CreateImage(string str_ValidateCode)
        private Bitmap CreateImage(string str_ValidateCode) {
        { Random newRandom = new Random((int)DateTime.Now.Ticks);
            Random newRandom = new Random((int)DateTime.Now.Ticks); int int_ImageWidth = str_ValidateCode.Length * 14;
            int int_ImageWidth = str_ValidateCode.Length * 14; int int_ImageHeight = 20;
            int int_ImageHeight = 20; //  图高20px
            //  图高20px Bitmap theBitmap = new Bitmap(int_ImageWidth, int_ImageHeight);
            Bitmap theBitmap = new Bitmap(int_ImageWidth, int_ImageHeight); Graphics theGraphics = Graphics.FromImage(theBitmap);
            Graphics theGraphics = Graphics.FromImage(theBitmap); //  白色背景
            //  白色背景 theGraphics.Clear(Color.White);
            theGraphics.Clear(Color.White); //  灰色边框
            //  灰色边框 theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, int_ImageHeight);
            theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, int_ImageHeight);
 int num = theBitmap.Width * theBitmap.Height * 30 / 100;
            int num = theBitmap.Width * theBitmap.Height * 30 / 100; for (int iCount = 0; iCount < num; iCount++)
            for (int iCount = 0; iCount < num; iCount++) {
            { // 在随机的位置使用随机的颜色设置图片的像素
                // 在随机的位置使用随机的颜色设置图片的像素 int x = newRandom.Next(theBitmap.Width);
                int x = newRandom.Next(theBitmap.Width); int y = newRandom.Next(theBitmap.Height);
                int y = newRandom.Next(theBitmap.Height); int r = newRandom.Next(255);
                int r = newRandom.Next(255); int g = newRandom.Next(255);
                int g = newRandom.Next(255); int b = newRandom.Next(255);
                int b = newRandom.Next(255); Color c = Color.FromArgb(r, g, b);
                Color c = Color.FromArgb(r, g, b); theBitmap.SetPixel(x, y, c);
                theBitmap.SetPixel(x, y, c); }//for
            }//for

 //  10pt的字体
            //  10pt的字体 Font theFont = new Font("Arial", 12, FontStyle.Bold);
            Font theFont = new Font("Arial", 12, FontStyle.Bold);
 for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
            for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++) {
            { string str_char = str_ValidateCode.Substring(int_index, 1);
                string str_char = str_ValidateCode.Substring(int_index, 1); Brush newBrush = new SolidBrush(GetColor());
                Brush newBrush = new SolidBrush(GetColor()); Point thePos = new Point(int_index * 13 + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
                Point thePos = new Point(int_index * 13 + 1 + newRandom.Next(3), 1 + newRandom.Next(3)); theGraphics.DrawString(str_char, theFont, newBrush, thePos);
                theGraphics.DrawString(str_char, theFont, newBrush, thePos); }
            } 
             theGraphics.Dispose();
            theGraphics.Dispose(); return theBitmap;
            return theBitmap; 
             }
        }
 IHttpHandler 成员
        IHttpHandler 成员 }
    } }
}IHttpHandle接口的ProcessRequest方法可以启用 HTTP Web 请求的处理。
类VerifyImageHttpHandle 继承了IHttpHandle接口用于自定义程序处理的Web请求。然后在web.config的<system.web>节中配置
 <httpHandlers>
      <httpHandlers> <add verb="*" path="VerifyImg.jd" type="jdTools.Web.VerifyImageHttpHandle"/>
        <add verb="*" path="VerifyImg.jd" type="jdTools.Web.VerifyImageHttpHandle"/> </httpHandlers>
      </httpHandlers>此时在浏览器中访问VerifyImg.jd时就会得到一个验证码图片,生成验证码的内容就完成了。
现在我们要自定义一个WEB自定义控件。其代码如下:
 using System;
using System; using System.Collections.Generic;
using System.Collections.Generic; using System.ComponentModel;
using System.ComponentModel; using System.Text;
using System.Text; using System.Web;
using System.Web; using System.Web.UI;
using System.Web.UI; using System.Web.UI.WebControls;
using System.Web.UI.WebControls;

 namespace jdTools.Web.UI
namespace jdTools.Web.UI {
{ [ToolboxData("<{0}:VerifyImage runat=server></{0}:VerifyImage>")]
    [ToolboxData("<{0}:VerifyImage runat=server></{0}:VerifyImage>")] public class VerifyImage : WebControl
    public class VerifyImage : WebControl {
    { public string Value
        public string Value {
        { get { return HttpContext.Current.Session["Verify"].ToString(); }
            get { return HttpContext.Current.Session["Verify"].ToString(); } }
        } public virtual ImageAlign ImageAlign
        public virtual ImageAlign ImageAlign {
        { get
            get {
            { object obj2 = this.ViewState["ImageAlign"];
                object obj2 = this.ViewState["ImageAlign"]; if (obj2 != null)
                if (obj2 != null) {
                { return (ImageAlign)obj2;
                    return (ImageAlign)obj2; }
                } return ImageAlign.NotSet;
                return ImageAlign.NotSet; }
            } set
            set {
            { if ((value < ImageAlign.NotSet) || (value > ImageAlign.TextTop))
                if ((value < ImageAlign.NotSet) || (value > ImageAlign.TextTop)) {
                { throw new ArgumentOutOfRangeException("value");
                    throw new ArgumentOutOfRangeException("value"); }
                } this.ViewState["ImageAlign"] = value;
                this.ViewState["ImageAlign"] = value; }
            }
 }
        }
 public VerifyImage()
        public VerifyImage() : base(HtmlTextWriterTag.Img)
            : base(HtmlTextWriterTag.Img) { }
        { } protected override void AddAttributesToRender(HtmlTextWriter writer)
        protected override void AddAttributesToRender(HtmlTextWriter writer) {
        { base.AddAttributesToRender(writer);
            base.AddAttributesToRender(writer); writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer"); writer.AddAttribute("onclick", "this.src='VerifyImg.jd?id='+Math.random()", true);
            writer.AddAttribute("onclick", "this.src='VerifyImg.jd?id='+Math.random()", true); writer.AddAttribute(HtmlTextWriterAttribute.Src, "VerifyImg.jd");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, "VerifyImg.jd"); string str2;
            string str2; switch (this.ImageAlign)
            switch (this.ImageAlign) {
            { case ImageAlign.Left:
                case ImageAlign.Left: str2 = "left";
                    str2 = "left"; break;
                    break;
 case ImageAlign.Right:
                case ImageAlign.Right: str2 = "right";
                    str2 = "right"; break;
                    break;
 case ImageAlign.Baseline:
                case ImageAlign.Baseline: str2 = "baseline";
                    str2 = "baseline"; break;
                    break;
 case ImageAlign.Top:
                case ImageAlign.Top: str2 = "top";
                    str2 = "top"; break;
                    break;
 case ImageAlign.Middle:
                case ImageAlign.Middle: str2 = "middle";
                    str2 = "middle"; break;
                    break;
 case ImageAlign.Bottom:
                case ImageAlign.Bottom: str2 = "bottom";
                    str2 = "bottom"; break;
                    break;
 case ImageAlign.AbsBottom:
                case ImageAlign.AbsBottom: str2 = "absbottom";
                    str2 = "absbottom"; break;
                    break;
 case ImageAlign.AbsMiddle:
                case ImageAlign.AbsMiddle: str2 = "absmiddle";
                    str2 = "absmiddle"; break;
                    break;
 case ImageAlign.NotSet:
                case ImageAlign.NotSet: str2="";
                    str2=""; break;
                    break; default:
                default: str2 = "texttop";
                    str2 = "texttop"; break;
                    break; }
            } if (str2 != "")
            if (str2 != "") writer.AddAttribute(HtmlTextWriterAttribute.Align, str2);
                writer.AddAttribute(HtmlTextWriterAttribute.Align, str2); }
        } }
    } }
}
VerifyImage 类定义了两个属性。其中Value属性用于取得session中存放的验证码的值。
这里就很简单了,没有必要详说。
在使用的时候aspx页面如下:
 <ul>
                    <ul> <li>用户名:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></li>
                        <li>用户名:<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></li> <li>密 码:<asp:TextBox ID="txtPassWord" runat="server"></asp:TextBox></li>
                        <li>密 码:<asp:TextBox ID="txtPassWord" runat="server"></asp:TextBox></li> <li>检证码:<asp:TextBox ID="txtVerify" runat="server" Width="50px"></asp:TextBox><jd:VerifyImage ID="verify" runat="server" Height="23px" ImageAlign="AbsMiddle"/></li>
                        <li>检证码:<asp:TextBox ID="txtVerify" runat="server" Width="50px"></asp:TextBox><jd:VerifyImage ID="verify" runat="server" Height="23px" ImageAlign="AbsMiddle"/></li> </ul>
                    </ul>aspx.cs中:
 if (txtVerify.Text != verify.Value)
            if (txtVerify.Text != verify.Value) {
            { //
                // .验证码错误
.验证码错误 }
            } else
            else {
            { //
                // 验证码正确
验证码正确 }
            } 
                    
                
 

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号