Login 图片验证码, 用一个aspx页面作为图片验证码

第二种是:比较简单,生成的不是图片,是span和文字版的验证码

1、类库文件

<ccid_nobr>
<ccid_code>using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Web.UI;

using System.ComponentModel;

using System.Web.UI.WebControls;

using System.Drawing;

using System.Web;

using System.IO;



namespace MyControls

{

    [ParseChildren(false)]

    [DefaultProperty("Text")]

    [ToolboxData("<{0}:ValidateControl runat=server></{0}:ValidateControl>")]

    public class ValidateControl : WebControl

    {

        public ValidateControl() : base(HtmlTextWriterTag.Img)

        { }

        



        #region 属性



        [Category("Appearance"),

 PersistenceMode(PersistenceMode.InnerDefaultProperty),

 Bindable(true), DefaultValue("GBK5"), 

Localizable(true), Description("Label_Text")]

        public virtual string Text

        {

            get

            {

                String s = (String)ViewState["Text"];

                return ((s == null) ? "GK4W" : s);

            }

            set

            {

                ViewState["Text"] = value;

            }

        }



        [BrowsableAttribute(true)]

        [DescriptionAttribute("背景图片")]

        [CategoryAttribute("Appearance")]

        public virtual String ImageUrl

        {

            get { return ViewState["ImageUrl"] != null ? (string)ViewState["ImageUrl"] : ""; }

            set { ViewState["ImageUrl"] = value; }

        }



        [BrowsableAttribute(true)]

        [DescriptionAttribute("数据位数")]

        [CategoryAttribute("Appearance")]

        public virtual int Step

        {

            get { return ViewState["Step"] != null ? (int)ViewState["Step"] : 4; }

            set { ViewState["Step"] = value; }

        }



        [BrowsableAttribute(true)]

        [DescriptionAttribute("文本位置")]

        [CategoryAttribute("Appearance")]

        public virtual TextAlign TextAlign

        {

            get { return ViewState["TextAlign"] != null ? 

(TextAlign)ViewState["TextAlign"] : 

DX.GO.Portal.Web.Controls.TextAlign.center; }

            set { ViewState["TextAlign"] = value; }

        }



        protected override HtmlTextWriterTag TagKey

        {

            get

            {

                return HtmlTextWriterTag.Span;

            }

        }

        #endregion



        #region 初始化



        protected override void OnLoad(EventArgs e)

        {

            Text = GenerateCheckCode(Step);

            //CreateCheckCodeImage(Text);

            base.OnLoad(e);

        }

        #endregion



        #region 内部方法



        /// <summary>

        /// 产生随机字符串

        /// </summary>

        /// <param name="num">int</param>

        /// <returns>string</returns>

        private string GenerateCheckCode(int num)

        {

            #region 

            //string[] source ={"0","1","2","3","4","5","6","7","8","9",

            //                    "A","B","C","D","E","F","G","H","I","J","K","L","M","N",

            //                    "O","P","Q","R","S","T","U","V","W","X","Y","Z"};

            //string code = "";

            //Random rd = new Random();

            //for (int i = 0; i < num; i++)

            //{

            //    code += source[rd.Next(0, source.Length)];

            //}

            //return code;

            #endregion



            int number;

            char code;

            string checkCode = String.Empty;



            Random random = new Random();

            for (int i = 0; i < num; i++)

            {

                number = random.Next();



                if (number % 2 == 0)

                    code = (char)('0' + (char)(number % 10));

                else

                    code = (char)('A' + (char)(number % 26));



                checkCode += code.ToString();

            }

            return checkCode;

        }



        /// <summary>

        /// 生成图片

        /// </summary>

        /// <param name="checkCode">string</param>

        private void CreateCheckCodeImage(string checkCode)

        {

            if (checkCode == null || checkCode.Trim() == String.Empty)

                return;



            //Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);

          

            Bitmap image = new Bitmap((int)this.Width.Value,(int)this.Height.Value);

            Graphics g = Graphics.FromImage(image);



            try

            {

                //生成随机生成器

                Random random = new Random();



                //清空图片背景色

                g.Clear(Color.White);



                //画图片的背景噪音线

                for (int i = 0; i < 25; i++)

                {

                    int x1 = random.Next(image.Width);

                    int x2 = random.Next(image.Width);

                    int y1 = random.Next(image.Height);

                    int y2 = random.Next(image.Height);



                    g.DrawLine(new Pen(Color.GreenYellow), x1, y1, x2, y2);

                }



                Font font = new System.Drawing.

Font("Verdana", 12, (System.Drawing.FontStyle.Bold |

 System.Drawing.FontStyle.Italic));

                System.Drawing.Drawing2D.

LinearGradientBrush brush = 

new System.Drawing.Drawing2D.LinearGradientBrush

(new Rectangle(0, 0, image.Width, image.Height),

 Color.Blue, Color.DarkRed, 1.2f, true);

                g.DrawString(checkCode, font, brush, 2, 2);



                //画图片的前景噪音点

                for (int i = 0; i < 80; i++)

                {

                    int x = random.Next(image.Width);

                    int y = random.Next(image.Height);



                    image.SetPixel(x, y, Color.FromArgb(random.Next()));

                }



                //画图片的边框线

                g.DrawRectangle(new Pen(Color.Red), 0, 0, image.Width - 1, image.Height - 1);



                System.IO.MemoryStream ms = new System.IO.MemoryStream();

                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);



                System.Web.HttpContext.Current.Response.ClearContent();

                System.Web.HttpContext.Current.Response.ContentType = "image/Gif";

                System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());

                System.Web.HttpContext.Current.Response.End();

            }

            finally

            {

                g.Dispose();

                image.Dispose();

            }

        }





        #endregion



        #region 呈现



        /// <summary>

        /// 应用最外层标签的属性和样式属性

        /// </summary>

        /// <param name="writer"></param>

        protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)

        {

            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);

            writer.AddStyleAttribute(HtmlTextWriterStyle.Height, Convert.ToString(Height));

            writer.AddStyleAttribute(HtmlTextWriterStyle.Width, Convert.ToString(Width));

            writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundImage, ImageUrl);

            writer.AddStyleAttribute(HtmlTextWriterStyle.TextAlign, Convert.ToString(TextAlign));

            base.AddAttributesToRender(writer);

        }



        /// <summary>

        /// 过滤

        /// </summary>

        /// <param name="obj"></param>

        protected override void AddParsedSubObject(object obj)

        {

            //if (!(obj is LiteralControl))

            //    return;

            //base.AddParsedSubObject(obj);

        }



        /// <summary>

        /// 呈现最外层标签的内容

        /// </summary>

        /// <param name="output"></param>

        protected override void RenderContents(HtmlTextWriter output)

        {

            output.Write(Text);

            base.RenderContents(output);

        }



        #endregion

    }

}





using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace MyControls

{

    public enum TextAlign

    {

        right, center, left

    }

}

2、生成文件,添加到工具箱,拖到页面就可以使用

<ccid_nobr>
<ccid_code><go:ValidateControl ID="ValidateControl1" 

runat="server" BackColor="#CC3300" 

                                                

BorderStyle="Solid" BorderWidth=

"1px" Font-Bold="True" Font-Italic="True" 

                                                

Font-Names="Arial Black" Font-Size="Small" Step="5" Width="70px">

</go:ValidateControl>

3、验证方法

<ccid_nobr>
<ccid_code>string vcode = string.Empty;        

       protected void Page_Load(object sender, EventArgs e)

        {

            vcode = ((ValidateControl)this.Login.FindControl("ValidateControl1")).Text.ToLower();

        }

   

       protected void Login_Authenticate(object sender, AuthenticateEventArgs args)

        {

            string Codetext = ((TextBox)this.Login.FindControl("txtValidateCode")).Text.ToLower();

           if (Codetext == null)

            {

                this.Login.FailureText = "验证码不能为空!";

                args.Authenticated = false;

                return;

            }



           if (vcode == Codetext)

           {

               AuthLogCount(mycount.LogCounts, args);

           }

           else

           {

               this.Login.FailureText = "验证码输入不正确!";

               args.Authenticated = false;

               return;

           }

        }

你可能感兴趣的:(login)