你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / 数据库开发
ASP.NET图片验证码控件实现系统登录验证全过程
 
最近在做系统的时候,希望登录的时候要有登录验证,也就是验证码的功能,把实现贴出来,大家共享,共有两种方法。

第一种是:可以产生图片的图片验证码

1、类库文件

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.UI.WebControls;
    using System.ComponentModel; 
    using System.Web.UI;

    namespace AuthCode
    {
    [Description("图形验证码控件"),
ToolboxData("<{0}:ImageAuthCode runat=server>
</{0}:ImageAuthCode>")]
    public class ImageAuthCode:Image
    {
        [Description("图形验证码产生网页地址"), DefaultValue("")]
        public string ValidateCodeUrl { get; set; }

        protected override void Render(HtmlTextWriter writer)
        {
            string sUrl, sScript;

            sUrl = this.ValidateCodeUrl;

            if (string.IsNullOrEmpty(sUrl))
            {
                sUrl = "~/AuthCode.ashx";
            }

            if (this.BorderWidth == Unit.Empty)
            {
                this.BorderWidth = Unit.Pixel(1);
            }

            if (this.AlternateText == string.Empty)
            {
                this.AlternateText = "图形验证码";
            }

            this.ToolTip = "鼠标单击可以产生新的验证码";
            this.ImageUrl = sUrl;

            if (!this.DesignMode)
            {
                sScript = String.Format("this.src='{0}?
flag='+Math.random();", 
this.Page.ResolveClientUrl(sUrl));
                this.Attributes["onclick"] = sScript;
            }

            this.Style[HtmlTextWriterStyle.Cursor] = "pointer";

            base.Render(writer);
        }

        public bool ValidateCode(string Code)
        {
            if (this.Page.Session["CheckCode"] == null)
                return false;

            if (this.Page.Session["CheckCode"].ToString() == Code)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

2、ashx文件如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Web.SessionState;

namespace MyAuthCode
{
    /// <summary>
    /// Summary description for AuthCode
    /// </summary>
    public class AuthCode : IHttpHandler, IRequiresSessionState 
    {
        private void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

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

            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.Silver), 
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 < 100; 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.Silver), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ContentType = "image/Gif";
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        private string GenerateCheckCode()
        {
            int number;
            char code;
            string checkCode = String.Empty;

            System.Random random = new Random();

            for (int i = 0; i < 5; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));

                checkCode += code.ToString();
            }
            
            HttpContext.Current.Session.Add("CheckCode", checkCode.Trim().ToLower());
            //将 checkCode 写入 Session 中

            return checkCode;
        }

        public void ProcessRequest(HttpContext context)
        {
            this.CreateCheckCodeImage(GenerateCheckCode());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

3、增加工具箱和拖到页面使用

<%@ Register assembly="AuthCode" namespace="AuthCode" tagprefix="cc1" %>
<cc1:ImageAuthCode ID="ImageAuthCode1" runat="server" Height="20px" Width="100px"/>

4、验证方法

ImageAuthCode1.ValidateCode(TextBox1.Text.Trim().ToString()) 结果返回true或者false.

5、最重要的一点修改Web.Config配置文件

<location path="AuthCode.ashx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>

如果不增加此段代码,当你的时,图片验证码是无法显示的,因为它没有权限。第二种方法就不需要增加此段代码。

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

1、类库文件

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、生成文件,添加到工具箱,拖到页面就可以使用

<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、验证方法

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;
           }
        }

好了,完了,就是这些了,可以直接使用。大家可以扩展。

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089