首页 > 代码库 > 验证码几个小例

验证码几个小例

例一:

在网站要目录下添加ValidateCode.aspx,路径自己定。

ValidateCode.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidateCode.aspx.cs" Inherits="ValidateCode_ValidateCode" %>

 ValidateCode.aspx.cs:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

public partial class ValidateCode_ValidateCode : System.Web.UI.Page
{
    private int letterWidth = 15;//单个字体的宽度范围
    private int letterHeight = 27;//单个字体的高度范围
    private int letterCount = 5;//验证码位数
    private char[] chars = "23456789QWERTYUPASDFGHJKLZXCVBNMqwertyupasdfghjkzxcvbnm".ToCharArray();
    private string[] fonts = { "Arial", "Georgia" };
    /// <summary>
    /// 产生波形滤镜效果
    /// </summary>
    private const double PI = 3.1415926535897932384626433832795;
    private const double PI2 = 6.283185307179586476925286766559;
    protected void Page_Load(object sender, EventArgs e) {
        //防止网页后退--禁止缓存    
        Response.Expires = 0;
        Response.Buffer = true;
        Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
        Response.AddHeader("pragma", "no-cache");
        Response.CacheControl = "no-cache";
        string str_ValidateCode = GetRandomNumberString(letterCount);
        HttpCookie objCookie = new HttpCookie("ValidateCode");
        objCookie.Value = str_ValidateCode.ToLower();
        objCookie.Path = "/";
        objCookie.Expires = DateTime.Now.AddSeconds(1200);
        Response.Cookies.Add(objCookie);
        CreateImage(str_ValidateCode);

    }
    public void CreateImage(string checkCode) {
        int int_ImageWidth = checkCode.Length * letterWidth + 5;
        Random newRandom = new Random();
        Bitmap image = new Bitmap(int_ImageWidth, letterHeight);
        Graphics g = Graphics.FromImage(image);
        //生成随机生成器
        Random random = new Random();
        //白色背景
        g.Clear(Color.White);
        //画图片的背景噪音线
        for (int i = 0; i < 10; 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);
        }

        //画图片的前景噪音点
        for (int i = 0; i < 10; i++) {
            int x = random.Next(image.Width);
            int y = random.Next(image.Height);

            image.SetPixel(x, y, Color.FromArgb(random.Next()));
        }
        //随机字体和颜色的验证码字符

        int findex;
        for (int int_index = 0; int_index < checkCode.Length; int_index++) {
            findex = newRandom.Next(fonts.Length - 1);
            string str_char = checkCode.Substring(int_index, 1);
            Brush newBrush = new SolidBrush(GetRandomColor());
            Point thePos = new Point(int_index * letterWidth + 1 + newRandom.Next(3), 1 + newRandom.Next(3));//5+1+a+s+p+x
            g.DrawString(str_char, new Font(fonts[findex], 14, FontStyle.Bold), newBrush, thePos);
        }
        //灰色边框
        g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1));
        //图片扭曲
        //image = TwistImage(image, true, 3, 4);
        //将生成的图片发回客户端
        MemoryStream ms = new MemoryStream();
        image.Save(ms, ImageFormat.Png);
        Response.ClearContent(); //需要输出图象信息 要修改HTTP头 
        Response.ContentType = "image/Png";
        Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
    }
    /// <summary>
    /// 正弦曲线Wave扭曲图片
    /// </summary>
    /// <param name="srcBmp">图片路径</param>
    /// <param name="bXDir">如果扭曲则选择为True</param>
    /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
    /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
    /// <returns></returns>
    public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase) {
        System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

        // 将位图背景填充为白色
        System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);

        graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);

        graph.Dispose();

        double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

        for (int i = 0; i < destBmp.Width; i++) {
            for (int j = 0; j < destBmp.Height; j++) {
                double dx = 0;

                dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;

                dx += dPhase;

                double dy = Math.Sin(dx);

                // 取得当前点的颜色
                int nOldX = 0, nOldY = 0;

                nOldX = bXDir ? i + (int)(dy * dMultValue) : i;

                nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                System.Drawing.Color color = srcBmp.GetPixel(i, j);
                if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height) {
                    destBmp.SetPixel(nOldX, nOldY, color);
                }
            }
        }
        return destBmp;
    }
    public Color GetRandomColor() {
        Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
        System.Threading.Thread.Sleep(RandomNum_First.Next(50));
        Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
        int int_Red = RandomNum_First.Next(210);
        int int_Green = RandomNum_Sencond.Next(180);
        int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
        int_Blue = (int_Blue > 255) ? 255 : int_Blue;
        return Color.FromArgb(int_Red, int_Green, int_Blue);
    }
    //  生成随机数字字符串
    public string GetRandomNumberString(int int_NumberLength) {
        Random random = new Random();
        string validateCode = string.Empty;
        for (int i = 0; i < int_NumberLength; i++)
            validateCode += chars[random.Next(0, chars.Length)].ToString();
        return validateCode;
    }
}
View Code

使用时:

放在页面前
<span>验证码:</span>
<input name="txtCode" runat="server" type="text" id="txtCode" class="txtinput1" />
<img class="txtverity" onclick="this.src=http://www.mamicode.com/this.src+‘?‘" src="http://www.mamicode.com/ValidateCode/ValidateCode.aspx" style="cursor: pointer" alt="看不清楚,换一张" title="看不清楚,换一张" />

//onclick="this.src=http://www.mamicode.com/‘ValifyCode.aspx?r=‘ + Math.random();

放在页面后
protected void btnSendMsg_Click(object sender, EventArgs e) {
if (Request.Cookies["ValidateCode"] == null) {
ScriptManager.RegisterStartupScript(this, GetType(), "msg", "alert(‘您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。‘)", true);

return;
}
else {

if (string.Compare(Request.Cookies["ValidateCode"].Value, txtCode.Value.Trim().ToLower(), true) == 0) {
insertMsgToUs();
}
else {
ScriptManager.RegisterStartupScript(this, GetType(), "msg", "alert(‘验证码不正确!‘)", true);
}
}
}

 

例二:

在网站根目录下添加自定义控件VerifyImage.ashx:

<%@ WebHandler Language="C#"  Class="VerifyImage" %>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

    /// <summary>
    /// 生成验证码
    /// </summary>
    public  class VerifyImage : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            VerifyImage v = new VerifyImage();
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);//如不加,单击验证图片'看不清换一张'

            v.Length = this.length;
            v.FontSize = this.fontSize;
            v.Chaos = this.chaos;
            v.BackgroundColor = this.backgroundColor;
            v.ChaosColor = this.chaosColor;
            v.CodeSerial = this.codeSerial;
            v.Colors = this.colors;
            v.Fonts = this.fonts;
            v.Padding = this.padding;
            string code = v.CreateVerifyCode();        //取随机码
            v.CreateImageOnPage(code, context);        // 输出图片

            context.Response.Cookies.Add(new HttpCookie("VerifyCode", code.ToUpper()));// 使用Cookies取验证码的值
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region 验证码长度(默认6个验证码的长度)
        int length = 5;
        public int Length
        {
            get { return length; }
            set { length = value; }
        }
        #endregion

        #region 验证码字体大小(为了显示扭曲效果,默认40像素,可以自行修改)
        int fontSize = 12;
        public int FontSize
        {
            get { return fontSize; }
            set { fontSize = value; }
        }
        #endregion

        #region 边框补(默认1像素)
        int padding = 2;
        public int Padding
        {
            get { return padding; }
            set { padding = value; }
        }
        #endregion

        #region 是否输出燥点(默认不输出)
        bool chaos = true;
        public bool Chaos
        {
            get { return chaos; }
            set { chaos = value; }
        }
        #endregion

        #region 输出燥点的颜色(默认灰色)
        Color chaosColor = Color.LightGray;
        public Color ChaosColor
        {
            get { return chaosColor; }
            set { chaosColor = value; }
        }
        #endregion

        #region 自定义背景色(默认白色)
        Color backgroundColor = Color.White;
        public Color BackgroundColor
        {
            get { return backgroundColor; }
            set { backgroundColor = value; }
        }
        #endregion

        #region 自定义随机颜色数组
        Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
        public Color[] Colors
        {
            get { return colors; }
            set { colors = value; }
        }
        #endregion

        #region 自定义字体数组
        string[] fonts = { "Arial", "Georgia" };
        public string[] Fonts
        {
            get { return fonts; }
            set { fonts = value; }
        }
        #endregion

        #region 自定义随机码字符串序列(使用逗号分隔)
        string codeSerial = "1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
        public string CodeSerial
        {
            get { return codeSerial; }
            set { codeSerial = value; }
        }
        #endregion

        #region 产生波形滤镜效果

        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 6.283185307179586476925286766559;

        /// <summary>
        /// 正弦曲线Wave扭曲图片
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
        /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
        /// <returns></returns>
        public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();

            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);

                    // 取得当前点的颜色
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                     && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }

            return destBmp;
        }

        #endregion

        #region 生成校验码图片
        public Bitmap CreateImageCode(string code)
        {
            int fSize = FontSize;
            int fWidth = fSize + Padding;

            int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
            int imageHeight = fSize * 2 + Padding;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);

            Graphics g = Graphics.FromImage(image);

            g.Clear(BackgroundColor);

            Random rand = new Random();

            //给背景添加随机生成的燥点
            if (this.Chaos)
            {

                Pen pen = new Pen(ChaosColor, 0);
                int c = Length * 10;

                for (int i = 0; i < c; i++)
                {
                    int x = rand.Next(image.Width);
                    int y = rand.Next(image.Height);

                    g.DrawRectangle(pen, x, y, 1, 1);
                }
            }

            int left = 0, top = 0, top1 = 1, top2 = 1;

            int n1 = (imageHeight - FontSize - Padding * 2);
            int n2 = n1 / 4;
            top1 = n2;
            top2 = n2 * 2;

            Font f;
            Brush b;

            int cindex, findex;

            //随机字体和颜色的验证码字符
            for (int i = 0; i < code.Length; i++)
            {
                cindex = rand.Next(Colors.Length - 1);
                findex = rand.Next(Fonts.Length - 1);

                f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
                b = new System.Drawing.SolidBrush(Colors[cindex]);

                if (i % 2 == 1)
                {
                    top = top2;
                }
                else
                {
                    top = top1;
                }

                left = i * fWidth;

                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }

            //画一个边框 边框颜色为Color.Gainsboro
            //g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            //g.Dispose();

            //产生波形
            //image = TwistImage(image, true, 8, 4);
            image = TwistImage(image, true, 0, 0);

            return image;
        }
        #endregion

        #region 将创建好的图片输出到页面
        public void CreateImageOnPage(string code, HttpContext context)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            Bitmap image = this.CreateImageCode(code);

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

            context.Response.ClearContent();
            context.Response.ContentType = "image/Jpeg";
            context.Response.BinaryWrite(ms.GetBuffer());

            ms.Close();
            ms = null;
            image.Dispose();
            image = null;
        }
        #endregion

        #region 生成随机字符码
        public string CreateVerifyCode(int codeLen)
        {
            if (codeLen == 0)
            {
                codeLen = Length;
            }

            string[] arr = CodeSerial.Split(,);

            string code = "";

            int randValue = http://www.mamicode.com/-1;

            Random rand = new Random(unchecked((int)DateTime.Now.Ticks));

            for (int i = 0; i < codeLen; i++)
            {
                randValue = rand.Next(0, arr.Length - 1);

                code += arr[randValue];
            }

            return code;
        }
        public string CreateVerifyCode()
        {
            return CreateVerifyCode(0);
        }
        #endregion
    }
View Code

使用时:

放在页面前
<span>验证码:</span>
<input name="txtCode" runat="server" type="text" id="txtCode" class="txtinput1" />
<img src="http://www.mamicode.com/VerifyImage.ashx" class="txtverity" onclick="this.src=http://www.mamicode.com/this.src+‘?‘" alt="点击刷新验证码"/>

放在页面后
protected void btnSendMsg_Click(object sender, EventArgs e) {
if (Request.Cookies["VerifyCode"] == null) {
ScriptManager.RegisterStartupScript(this, GetType(), "msg", "alert(‘您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。‘)", true);

return;
}
else {

if (string.Compare(Request.Cookies["VerifyCode"].Value, txtCode.Value.Trim().ToUpper(), true) == 0) {
insertMsgToUs();
}
else {
ScriptManager.RegisterStartupScript(this, GetType(), "msg", "alert(‘验证码不正确!‘)", true);
}
}
}

 

例三:

添加ValidateCode.aspx,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public partial class ValidateCode : System.Web.UI.Page
{
    private void CreateImage(string checkCode)
        {
            int width = checkCode.Length * 14;
            Bitmap image = new Bitmap(width, 20);
            Graphics graphics = Graphics.FromImage(image);
            Font font = new Font("Arial ", 10f);
            Brush brush = new SolidBrush(Color.Black);
            Brush brush2 = new SolidBrush(Color.FromArgb(0xa6, 8, 8));
            graphics.Clear(ColorTranslator.FromHtml("#99C1CB"));
            char[] chArray = checkCode.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                if ((chArray[i] >= 0) && (chArray[i] <= 9))
                {
                    graphics.DrawString(chArray[i].ToString(), font, brush2, (float) (3 + (i * 12)), 3f);
                }
                else
                {
                    graphics.DrawString(chArray[i].ToString(), font, brush, (float) (3 + (i * 12)), 3f);
                }
            }
            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Jpeg);
            base.Response.Cache.SetNoStore();
            base.Response.ClearContent();
            base.Response.ContentType = "image/Jpeg";
            base.Response.BinaryWrite(stream.ToArray());
            graphics.Dispose();
            image.Dispose();
        }

        private string CreateRandomCode(int codeCount)
        {
            string[] strArray = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z".Split(new char[] { , });
            string str2 = "";
            int num = -1;
            Random random = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (num != -1)
                {
                    random = new Random((i * num) * ((int) DateTime.Now.Ticks));
                }
                int index = random.Next(0x23);
                if (num == index)
                {
                    return this.CreateRandomCode(codeCount);
                }
                num = index;
                str2 = str2 + strArray[index];
            }
            return str2;
        }

        private string GetRandomCode(int CodeCount)
        {
            string[] strArray = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z".Split(new char[] { , });
            string str2 = "";
            int num = -1;
            Random random = new Random();
            for (int i = 0; i < CodeCount; i++)
            {
                if (num != -1)
                {
                    random = new Random((num * i) * ((int) DateTime.Now.Ticks));
                }
                int index = random.Next(0x21);
                while (num == index)
                {
                    index = random.Next(0x21);
                }
                num = index;
                str2 = str2 + strArray[index];
            }
            return str2;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string randomCode = this.GetRandomCode(4);
            this.Session["CheckCode"] = randomCode;
            this.SetPageNoCache();
            this.CreateImage(randomCode);
        }

        private void SetPageNoCache()
        {
            base.Response.Buffer = true;
            base.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1.0);
            base.Response.Expires = 0;
            base.Response.CacheControl = "no-cache";
            base.Response.AppendHeader("Pragma", "No-Cache");
        }   
}
View Code

页面前面:
<script type="text/javascript">
function newGuid() {
var guid = "";
for (var i = 1; i <= 32; i++) {
var n = Math.floor(Math.random() * 16.0).toString(16);
guid += n;
if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
guid += "-";
}
return guid;
}
function ChangeCode() {
var myImg = document.getElementById("ImageCheck");
myImg.src = "http://www.mamicode.com/ValidateCode.aspx?flag=" + newGuid();
return false;
}
</script>

<input name="CheckCode" class="txtinput1" runat="server" type="text" id="CheckCode"/>
<img id="ImageCheck" onclick="ChangeCode()" src="http://www.mamicode.com/ValidateCode.aspx" alt="看不清楚,换一张" title="看不清楚,换一张" />

页面后面:
protected void btnSendMsg_Click(object sender, EventArgs e) {
if ((this.Session["CheckCode"] != null) && (this.Session["CheckCode"].ToString() != "")) {
if (this.Session["CheckCode"].ToString().ToLower() != this.CheckCode.Value.ToLower()) {
//this.lblMsg.Text = "验证码错误!";
ScriptManager.RegisterStartupScript(this, GetType(), "msg", "alert(‘验证码不正确!‘)", true);
this.Session["CheckCode"] = null;
return;
}
this.Session["CheckCode"] = null;
insertMsgToUs();
}
else {
base.Response.Redirect("Login.aspx");
}
}

 

例四:

verificationcode.aspx.cs:

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

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
public partial class verificationcode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        string vVerificationCode = RandomCode("verificationcode", 4, true);
        Add("verificationcode", vVerificationCode.ToLower());   //Session中保存验证码
        CreateImage(vVerificationCode);
    }
    /// <summary>
    /// 从字符串里随机得到,规定个数的字符串.
    /// </summary>
    /// <param name="allChar"></param>
    /// <param name="CodeCount"></param>
    /// <param name="tSleep">是否要在生成前将当前线程阻止以避免重复</param>
    /// <returns></returns>
    public static string RandomCode(string byChar, int CodeCount, bool tSleep) {
        string randomChar = "";
        switch (byChar) {
            case "num":
                randomChar = "1,2,3,4,5,6,7,8,9";
                break;
            case "maxen":
                randomChar = "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";
                break;
            case "minien":
                randomChar = "a,b,c,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
                break;
            case "minien&num":
                randomChar = "1,2,3,4,5,6,7,8,9,a,b,c,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
                break;
            case "all":
                randomChar = "1,2,3,4,5,6,7,8,9,a,b,c,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,"
                    + "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";
                break;
            case "verificationcode":
                randomChar = "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";
                break;
            default:
                randomChar = byChar;
                break;
        }
        randomChar = randomChar.Replace(",", "");
        string RandomCode = "";
        if (tSleep) {
            System.Threading.Thread.Sleep(3);
        }
        char[] allCharArray = randomChar.ToCharArray();
        int n = allCharArray.Length;
        System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
        for (int i = 0; i < CodeCount; i++) {
            int rnd = random.Next(0, n);
            RandomCode += allCharArray[rnd];
        }
        return RandomCode;
    }
    /// <summary>
    /// 添加Session,有效期为20分钟
    /// </summary>
    /// <param name="strSessionName">Session对象名称</param>
    /// <param name="strValues">Session值数组</param>
    public static void Add(string strSessionName, string strValue) {
        HttpContext.Current.Session[strSessionName] = strValue;
        HttpContext.Current.Session.Timeout = 20;
    }
    #region 验证码
        ///  <summary>
        ///  创建验证码图片
        ///  </summary>
        ///  <param  name="randomcode">验证码</param>
        private void CreateImage(string randomcode)
        {
            int randAngle = 40; //随机转动角度
            int mapwidth = (int)(randomcode.Length * 18);
            Bitmap map = new Bitmap(mapwidth, 24);//创建图片背景
            Graphics graph = Graphics.FromImage(map);
            graph.Clear(Color.White);//清除画面,填充背景
            //graph.DrawRectangle(new Pen(Color.Silver, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框
            Random rand = new Random();
            //验证码旋转,防止机器识别
            char[] chars = randomcode.ToCharArray();//拆散字符串成单字符数组
            //文字距中
            StringFormat format = new StringFormat(StringFormatFlags.NoClip);
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.Blue, Color.Green, 
                            Color.Orange, Color.Brown, Color.DarkBlue };
            //画图片的背景噪音线
            for (int i = 0; i < 2; i++)
            {
                int x1 = rand.Next(10);
                int x2 = rand.Next(map.Width - 10, map.Width);
                int y1 = rand.Next(map.Height);
                int y2 = rand.Next(map.Height);
                graph.DrawLine(new Pen(c[rand.Next(7)]), x1, y1, x2, y2);
            }
            for (int i = 0; i < chars.Length; i++)
            {
                int cindex = rand.Next(7);
                int findex = rand.Next(5);
                Font f = new System.Drawing.Font("Arial", 18, System.Drawing.FontStyle.Regular);//字体样式(参数2为字体大小)
                Brush b = new System.Drawing.SolidBrush(c[cindex]);
                Point dot = new Point(12, 16);
                float angle = rand.Next(-randAngle, randAngle);//转动的度数
                graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
                graph.RotateTransform(angle);
                graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);
                graph.RotateTransform(-angle);//转回去
                graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
            }
            //生成图片
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/gif";
            Response.BinaryWrite(ms.ToArray());
            graph.Dispose();
            map.Dispose();
        }
        #endregion   
}
View Code

页面前面
<input name="txtCode" runat="server" type="text" id="txtCode" class="txtinput1" />
<img src="http://www.mamicode.com/verificationcode.aspx" onclick="this.src=http://www.mamicode.com/‘verificationcode.aspx?r=‘ + Math.random();" alt="点击刷新验证码" style="cursor: pointer;"/>

页面后面
protected void btnSendMsg_Click(object sender, EventArgs e) {
if ((this.Session["verificationcode"] != null) && (this.Session["verificationcode"].ToString() != "")) {
if (this.Session["verificationcode"].ToString() != this.txtCode.Value.ToLower()) {
ScriptManager.RegisterStartupScript(this, GetType(), "msg", "alert(‘验证码不正确!‘)", true);
this.Session["verificationcode"] = null;
return;
}
this.Session["verificationcode"] = null;
insertMsgToUs();
}
else {
base.Response.Redirect("Login.aspx");
}
}