asp.net验证码完整实例

Posted on 2009-06-14 20:53  口亻亻口  阅读(3338)  评论(0)    收藏  举报
验证码页面(代码全在后台):

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication2
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  // 验证码长度
  private int codeLen = 4;
  // 图片清晰度
  private int fineness =90;
  // 图片宽度
  private int imgWidth = 55;
  // 图片高度
  private int imgHeight = 24;
  // 字体家族名称
  private string fontFamily = "Times New Roman";
  // 字体大小
  private int fontSize = 14;
  // 字体样式
  private int fontStyle = 0;
  // 绘制起始坐标 X
  private int posX = 0;
  protected System.Web.UI.WebControls.Button Button1;
  // 绘制起始坐标 Y
  private int posY = 0;
  private void Page_Load(object sender, EventArgs e)
  {
   //读取 Request 传递参数#region 读取 Request 传递参数
   // 获取代码长度设置
   if (Request["CodeLen"] != null)
   {
    try
    {
     codeLen = Int32.Parse(Request["CodeLen"]);

    // 规定验证码长度
     if (codeLen < 4 || codeLen > 16)
      throw new Exception("验证码长度必须在4到16之间");
    }
    catch (Exception ex)
    {
     throw ex;
    }
   }

   // 获取图片清晰度设置
   if (Request["Fineness"] != null)
   {
    try
    {
     fineness = Int32.Parse(Request["Fineness"]);

     // 验证清晰度
     if (fineness < 0 || fineness > 100)
      throw new Exception("图片清晰度必须在0到100之间");
    }
    catch (Exception Ex)
    {
     throw Ex;
    }
   }

   // 获取图片宽度
   if (Request["ImgWidth"] != null)
   {
    try
    {
     imgWidth = Int32.Parse(Request["ImgWidth"]);

     if (imgWidth < 16 || imgWidth > 480)
      throw new Exception("图片宽度必须在16到480之间");
    }
    catch (Exception Ex)
    {
     throw Ex;
    }
   }

   // 获取图片高度
   if (Request["ImgHeight"] != null)
   {
    try
    {
     imgWidth = Int32.Parse(Request["ImgHeight"]);

     if (imgWidth < 16 || imgWidth > 320)
      throw new Exception("图片高度必须在16到320之间");
    }
    catch (Exception Ex)
    {
     throw Ex;
    }
   }

   // 获取验证码字体家族名称
   if (Request["FontFamily"] != null)
   {
    fontFamily = Request["FontFamily"];
   }

   // 获取验证码字体大小
   if (Request["FontSize"] != null)
   {
    try
    {
     fontSize = Int32.Parse(Request["FontSize"]);

     if (fontSize < 8 || fontSize > 72)
     throw new Exception("字体大小必须在8到72之间");
    }
    catch (Exception Ex)
   {
     throw Ex;
    }
  }

  // 获取字体样式
  if (Request["FontStyle"] != null)
   {
    try
    {
     fontStyle = Int32.Parse(Request["FontStyle"]);
    }
    catch (Exception Ex)
    {
     throw Ex;
    }
   }

   // 验证码绘制起始位置 X
   if (Request["PosX"] != null)
   {
    try
    {
     posX = Int32.Parse(Request["PosX"]);
    }
    catch (Exception Ex)
    {
     throw Ex;
    }
   }

   // 验证码绘制起始位置 Y
   if (Request["PosY"] != null)
   {
    try
   {
     posY = Int32.Parse(Request["PosY"]);
    }
    catch (Exception Ex)
    {
     throw Ex;
    }
   }

   string validateCode = CreateValidateCode();
   // 生成BITMAP图像
   Bitmap bitmap = new Bitmap(imgWidth, imgHeight);

   // 给图像设置干扰
   DisturbBitmap(bitmap);

   // 绘制验证码图像
   DrawValidateCode(bitmap, validateCode);

   // 保存验证码图像,等待输出
   bitmap.Save(Response.OutputStream, ImageFormat.Gif);
  }

 

  //------------------------------------------------------------
  // 随机生成验证码,并保存到SESSION中
  //------------------------------------------------------------
  public string CreateValidateCode()
  {
   string validateCode = "";

   // 随机数对象
   Random random = new Random();

   for (int i = 0; i < codeLen; i++)
   {
    // 26: a - z
    int n = random.Next(26);
           

    // 将数字转换成大写字母
    validateCode += (char)(n + 65);
   }
     
   // 保存验证码
   Session["ValidateCode"] = validateCode;
   return validateCode;
  }

  //------------------------------------------------------------
  // 为图片设置干扰点
  //------------------------------------------------------------
  private void DisturbBitmap(Bitmap bitmap)
  {
   // 通过随机数生成
   Random random = new Random();

   for (int i = 0; i < bitmap.Width; i++)
   {
    for (int j = 0; j < bitmap.Height; j++)
    {
     if (random.Next(100) <= this.fineness)
      bitmap.SetPixel(i, j, Color.White);
    }
   }
  }

  //------------------------------------------------------------
  // 绘制验证码图片
  //------------------------------------------------------------
  private void DrawValidateCode(Bitmap bitmap, string validateCode)
  {
   // 获取绘制器对象
   Graphics g = Graphics.FromImage(bitmap);

   // 设置绘制字体
   Font font = new Font(fontFamily, fontSize, GetFontStyle());

  // 绘制验证码图像
   g.DrawString(validateCode, font, Brushes.Black, posX, posY);
  }

  //------------------------------------------------------------
  // 换算验证码字体样式:1 粗体 2 斜体 3 粗斜体,默认为普通字体
 //------------------------------------------------------------
  private FontStyle GetFontStyle()
  {
   if (fontStyle == 1)
    return FontStyle.Bold;
   else if (fontStyle == 2)
    return FontStyle.Italic;
   else if (fontStyle == 3)
    return FontStyle.Bold | FontStyle.Italic;
   else
    return FontStyle.Regular;
  }


  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion
 }
}

调用验证码:

前台页面:

<%@ Page language="c#" Codebehind="WebForm2.aspx.cs" AutoEventWireup="false" Inherits="WebApplication2.WebForm2" %> <%@ Page language="c#" Codebehind="WebForm2.aspx.cs" AutoEventWireup="false" Inherits="WebApplication2.WebForm2" %> <%@ Page language="c#" Codebehind="WebForm2.aspx.cs" AutoEventWireup="false" Inherits="WebApplication2.WebForm2" %> <%@ Page language="c#" Codebehind="WebForm2.aspx.cs" AutoEventWireup="false"

Inherits="WebApplication2.WebForm2" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm2</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema"

content="http://schemas.microsoft.com/intellisense/ie5">
  <script language="javascript">
     function getcode()
   {
    document.getElementById("aaa").src="WebForm1.aspx"
   }
  </script>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <table  style="Z-INDEX: 101; LEFT: 104px; POSITION: absolute;

TOP: 64px">
    <tr>
     <td>用户名:</td>
     <td><asp:TextBox id="TextBox1"

runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>密码:</td>
     <td>
      <asp:TextBox id="TextBox2"

runat="server"></asp:TextBox>
     </td>
    </tr>
    <tr>
    <td>验证码:</td>
     <td>
      <asp:TextBox id="TextBox3"

runat="server"></asp:TextBox>
     </td>
    </tr>
    <tr>
     <td colspan="2">
      <img src="WebForm1.aspx" alt="验证码" id="aaa" onclick="getcode()"><a href="javascript:getcode()">
       刷新验证码</a>
     </td>
    </tr>
    <tr align="center">
     <td colspan="2"><asp:Button id="Button1"

runat="server" Text="Button"></asp:Button>
      <asp:Label id="Label1"

runat="server">Label</asp:Label></td>
    </tr>
   </table>
  </form>
 </body>
</HTML>
后台代码:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication2
{
 /// <summary>
 /// WebForm2 的摘要说明。
 /// </summary>
 public class WebForm2 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.TextBox TextBox1;
  protected System.Web.UI.WebControls.Label Label1;
  protected System.Web.UI.WebControls.TextBox TextBox2;
  protected System.Web.UI.WebControls.TextBox TextBox3;
  protected System.Web.UI.WebControls.Button Button1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Button1.Click += new System.EventHandler

(this.Button1_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Button1_Click(object sender, System.EventArgs e)
  {
   string b=Session["CheckCode"].ToString();
   if(this.TextBox3.Text.ToUpper()==b)
   {
    this.Label1.Text="成功";
   }
   else
   {
    this.Label1.Text="失败";
   }
  }
 }
}