陈斌彬的技术博客

Stay foolish,stay hungry

asp.net 验证码制作与验证

搭建环境-VS2010

新建 ASP.NET Web 应用程序,名称为 ValiDemo

img

项目目录结构

img

新建Default.aspx文件

img

<%@ Page Title="主页" Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ValiCodeDemo._Default" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>验证码测试</title>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <fieldset>
    <legend>验证码测试</legend>
        请输入验证码:<asp:TextBox ID="valid" runat="server"></asp:TextBox>  
        <asp:Image ID="Image1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="提交" onclick="Button1_Click" />
    </fieldset>
    </center>
    </form>
</body>
</html>

新建Default.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.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;

namespace ValiCodeDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Image1.ImageUrl = "ValiCode.aspx";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string ValiCode = valid.Text;
            if (ValiCode == "")
            {
                Response.Write("<script>alert('验证码为空!');</script>");
                valid.Focus();
                return;
            }
            else if (ValiCode != (string)Session["ValiCode"])
            {
                Response.Write("<script>alert('输入的验证码错误');</script>");
                valid.Text = "";
                valid.Focus();
            }
            else
            {
                Response.Write("<script>alert('你输入的验证码正确');</script>");
                valid.Text = "";
                valid.Focus();
            }
        }
    }
}

新建ValiCode.aspx文件

img

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ValiCode.aspx.cs" Inherits="ValiCodeDemo.ValiCode" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

或者使用母版页:

<%@ Page Title="主页" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
     <asp:Image ID="Image1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="提交" onclick="Button1_Click" />
</asp:Content>

新建ValiCode.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.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;       //引用Bitmap类和Graphics类来创建画板对象

namespace ValiCodeDemo
{
    public partial class ValiCode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DoImg(DoCode(5));
        }

        /// <summary>
        /// 生成验证码表达式
        /// </summary>
        /// <param name="num">验证码的长度</param>
        /// <returns>验证码表达式</returns>
        private string DoCode(int num)
        {
            //要从这个数组中随机取字符来生成验证码
            string[] Codesource ={"0","1","2","3","4","5","6","7","8","9",
                             "a","b","c","d","e","f","g","h","i","j","k","l","m","n"};
            string code = "";
            Random rd = new Random();
            for (int i = 0; i < num; i++)
            {
                code += Codesource[rd.Next(0, Codesource.Length)];
            }
            return code;
        }
        /// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="code">验证码表达式</param>
        private void DoImg(string code)
        {
            Random random = new Random();
            Bitmap mypalette = new Bitmap(100, 30);
            Graphics gh = Graphics.FromImage(mypalette);
            using (gh)
            {
                Rectangle rc = new Rectangle(0, 0, 100, 30);
                //填充图片
                gh.FillRectangle(new SolidBrush(Color.White), rc);
                for (int i = 0; i < 1; i++)
                {
                    int x1 = random.Next(mypalette.Width);
                    int x2 = random.Next(mypalette.Width);
                    int y1 = random.Next(mypalette.Height);
                    int y2 = random.Next(mypalette.Height);
                    //在图片上随机画线条
                    gh.DrawLine(new Pen(Color.Blue), x1, y1, x2, y2);
                }
                gh.DrawString(code, new Font("宋体", 20), new SolidBrush(Color.Black), rc);
                for (int i = 1; i < 60; i++)
                {
                    int x = random.Next(mypalette.Width);
                    int y = random.Next(mypalette.Height);
                    //在图片中填充随机颜色
                    mypalette.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //将生成的图像保存到流中
                mypalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                Session["ValiCode"] = code;                                                 //主要用来验证
            }
            Response.Write(code);
        }

    }
}

启动调试

img