用C#编写验证码的方法

这几天看了一些网友关于C#编写验证码的问题,特地关心了一下,自己整理了一些供大家参考学习!

一、验证码的C#源码如下(文件VerifyCode.aspx):

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.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace validateCode
{
    
/// <summary>
    
/// WebForm2 的摘要说明。
    
/// </summary>

    public class WebForm2 : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Image Image1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
this.CreateImage(GenerateCheckCode());
        }

        
private string GenerateCheckCode()
        
{
            
int number;
            
char code;
            
string checkCode = String.Empty;

            System.Random random 
= new Random();
            
for (int i = 0; i < 4; i++)
            
{
                number 
= random.Next();
                code 
= (char)('0' + (char)(number % 10));
                
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("myCheckCode", checkCode));

            
return checkCode;
        }

        
private void CreateImage(string checkCode)
        
{
            
int iwidth = (int)(checkCode.Length * 13);
            System.Drawing.Bitmap image 
= new System.Drawing.Bitmap(iwidth, 25);            
            Graphics g 
= Graphics.FromImage(image);
            g.Clear(Color.White);
            
//定义颜色
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
            
//定义字体
            string[] font = "Verdana""Microsoft Sans Serif""Comic Sans MS""Arial""宋体" };
            Random rand 
= new Random();
            
//随机输出噪点
            for (int i = 0; i < 2; i++)
            
{
                
int x = rand.Next(image.Width);
                
int y = rand.Next(image.Height);
                g.DrawRectangle(
new Pen(Color.LightGray, 0), x, y, 11);
            }


            
//输出不同字体和颜色的验证码字符
            for (int i = 0; i < checkCode.Length; i++)
            
{
                
int cindex = rand.Next(7);
                
int findex = rand.Next(5);

                Font f 
= new System.Drawing.Font(font[findex], 10, System.Drawing.FontStyle.Bold);

                Brush b 
= new System.Drawing.SolidBrush(c[cindex]);
                
int ii = 4;
                
if ((i + 1% 2 == 0)
                
{
                    ii 
= 2;
                }

                g.DrawString(checkCode.Substring(i, 
1), f, b, 3 + (i * 12), ii);
            }

            
//画一个边框
            g.DrawRectangle(new Pen(Color.Black,0), 00, image.Width - 2, image.Height - 2);
            
//输出到浏览器
            System.IO.MemoryStream ms = new System.IO.MemoryStream();            
//            image.Save("pic",System.Drawing.Imaging.ImageFormat.Jpeg);
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            Response.ClearContent();
            Response.ContentType 
= "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
//            this.Image1.ImageUrl="pic.jpg";
            g.Dispose();
            image.Dispose();
        }


        
Web 窗体设计器生成的代码
    }

}

二、C#验证码的使用方法:
在其他需要用到验证码的.aspx的html页里添加如下标签代码即可!
<img src="VerifyCode.aspx">
三、只刷新验证码的实现方法:
在上面的.aspx的html页添加如下代码:
<input class="buttonstyle" style="WIDTH: 120px" onclick="document.getElementById('imcheckingcode').src='VerifyCode.aspx?temp='+Math.random();" type="button" value="Change Code" />
四、在登录页面的登录按钮的处理事件中使用以下代码判断验证码:

private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
  
{
   
if(Request.Cookies["CheckCode"== null)
   
{
    lblMessage.Text 
= "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";
    lblMessage.Visible 
= true;
    
return;
   }
 

   
if(String.Compare(Request.Cookies["CheckCode"].Value, txtCheckCode.Text, true!= 0)
   
{
    lblMessage.Text 
= "验证码错误,请输入正确的验证码。";
    lblMessage.Visible 
= true;
    
return;
   }

以上整理的关于C#验证码资料,供大家参考,多提意见!!!
posted on 2007-01-12 16:24  虞山居士  阅读(935)  评论(1编辑  收藏  举报