日期:2011-11-16  浏览次数:20397 次

 

第一步生成验证码

新增一个ValidateCode.aspx页面

在ValidateCode.aspx.cs的代码如下

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Drawing.Imaging;

public partial class ValidateCode : System.Web.UI.Page
{   //该页面将用于生成验证码图片
    protected void Page_Load(object sender, EventArgs e)
    {     //调用函数将验证码生成图片
        this.CreateCheckCodeImage(GenerateCheckCode());
      
    }
    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();
        }

        //Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
       Session["CheckCode"] = checkCode;//用于客户端校验码比较

        return checkCode;
    }

    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