世界上有10种人:一种是懂二进制的,另一种是不懂的。

ASP .Net学习笔记之验证码实现

2010-03-24

最新开始学习ASP .Net,因为之前熟悉的是类C的编程语言,所以熟悉起来倒还没太多难度。下面要讲的是Web开发中经常要用到的验证码,先说一说如何用C#来实现它。
我们通常说的验证码,也可以称为CAPTCHA,也就是全自动区分计算机和人类的测试(CAPTCHA, Completely Automated Public Test to tell Computers and Humans Apart),是一种区分用户是计算机和人的公共全自动程序。在CAPTCHA测试中,作为服务器的计算机会自动生成一个问题由用户来解答。这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答CAPTCHA的问题,所以回答出问题的用户就可以被认为是人类。CAPTCHA目前广泛用于网站的留言板,许多留言板为防止有人利用计算机程序大量在留言板上张贴广告或其他垃圾信息,因此会放置CAPTCHA要求留言者必需输入图片上所显示的文数字或是算术题才可完成留言。而一些网络上的交易系统(如订票系统、网络银行)也为避免被计算机程序以暴力法大量尝试交易也会有CAPTCHA的机制。

实现思路:
1.随机生成一个固定长度的字符串,里面可以包含数字、字母甚至汉字都可以,存入一个Session变量中;
2.利用C#的图形相关类来绘制图片,显示在网页上;
3.将用户输入的内容与前面的Session变量进行比对;
下面是Captcha.aspx.cs的内容:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
 
namespace WebApplication2
{
    public partial class Captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string verifyCode = GetRandomString(4);
            this.CreateCaptcha(verifyCode);
            Session["verifyCode"] = verifyCode;
        }
 
        ///
        /// 产生一定长度的随机字符串
        ///
        ///
 
        ///
        private string GetRandomString(int length)
        {
            string[] characters = { "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" };
            int charactersLength = characters.Length;
            Random rd = new Random();
            string randomString = "";
            int indexNum = 0;
            for (int i = 0; i < length; i++)
            {
                indexNum = rd.Next(0, charactersLength - 1);    //随机产生索引值
                randomString += characters[indexNum];     //根据索引值取出字符数组中的字符
            }
            return randomString;
        }
 
        ///
        /// 生成图片
        ///
        ///
 
        private void CreateCaptcha(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;
 
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 13.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("Arial", 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);
                Response.ClearContent();
                Response.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
 
    }
}

怎么调用呢?在我们想要显示验证码的地方,通过img标签即可调用:

<img id="CodeImg" src="Captcha.aspx" alt="" />

注意这里的src属性必须填写验证码生成程序所对应的aspx页面地址,可以是相对地址也可以是绝对地址。
如果我们要加以完善,也就是万一遇到验证码显示不清楚的情况下,给用户提供刷新更换验证码的功能,实现起来也很简单:

<a onclick="document.getElementById('CodeImg').src='Captcha.aspx?tmp='+Math.random()" href="#">单击此处刷新验证码</a>

注意:这里的CodeImg对应的是你前面img标签的ID,必须要一致。
加上tmp=’+Math.random()这一参数的作用是避免缓存。

实际效果就是这样:

图1

图1

作者:admin | 分类目录:ASP .Net | 标签:

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">