ASP.net 验证码(C#)

public class ValidateCode : System.Web.UI.Page
 {
  private void Page_Load(object sender, System.EventArgs e)
  {
   this.CreateCheckCodeImage(GenerateCheckCode());
  }

  #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

  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));

   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.Next(image.Height);
     int y2 = random.Next(image.Height);

     g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
    }

    Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
    g.DrawString(checkCode, font, brush, 2, 2);

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

     image.SetPixel(x, y, Color.FromArgb(random.Next()));
    }

    //画图片的边框线
    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    Response.ClearContent();
    Response.ContentType = "image/Gif";
    Response.BinaryWrite(ms.ToArray());
   }
   finally
   {
    g.Dispose();
    image.Dispose();
   }
  }
 }

2....        

Asp.net(C#)实现验证码功能

Posted on 2004-10-20 17:03 边城浪子 阅读(6512) 评论(40)  编辑 收藏 收藏至365Key 所属分类: .NET(C#)

新建一个专门用来创建验证码图片的页面ValidateCode.aspx
它的后台cs文件代码如下:
PageLoad

private void Page_Load(object sender, System.EventArgs e)
        
{
            
string checkCode = CreateRandomCode(4);
            Session[
"CheckCode"= checkCode;
            CreateImage(checkCode);
        }

其中CreateRandomCode是自定义的函数,参数代表验证码位数

private string CreateRandomCode(int codeCount)
        
{
            
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z" ;
            
string[] allCharArray = allChar.Split(',');
            
string randomCode = "";
            
int temp = -1;

            Random rand 
= new Random();
            
for(int i = 0; i < codeCount; i++)
            
{
                
if(temp != -1)
                
{
                    rand 
= new Random(i*temp*((int)DateTime.Now.Ticks));
                }

                
int t = rand.Next(35);
                
if(temp == t)
                
{
                    
return CreateRandomCode(codeCount);
                }

                temp 
= t;
                randomCode 
+= allCharArray[t];
            }

            
return randomCode;
        }

CreateImage也是一个自定义的函数,用于生成图

private void CreateImage(string checkCode)
        
{
            
int iwidth = (int)(checkCode.Length * 11.5);
            System.Drawing.Bitmap image 
= new System.Drawing.Bitmap(iwidth, 20);
            Graphics g 
= Graphics.FromImage(image);
            Font f 
= new System.Drawing.Font("Arial"10, System.Drawing.FontStyle.Bold);
            Brush b 
= new System.Drawing.SolidBrush(Color.White);
            
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
            g.Clear(Color.Blue);
            g.DrawString(checkCode, f, b, 
33);

            Pen blackPen 
= new Pen(Color.Black, 0);
            Random rand 
= new Random();
            
for (int i=0;i<5;i++)
            
{
                
int y = rand.Next(image.Height);
                g.DrawLine(blackPen,
0,y,image.Width,y);
            }

            
            System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
            image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
            Response.ClearContent();
            Response.ContentType 
= "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }

//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
g.Clear(Color.Blue);
这两种方法都可以改变生成图片的背景颜色
下面那个for循环用来生成一些随机的水平线

在需要用到验证码的页面添加一个<asp:Image>控件即可,但是要把ImageUrl指向生成验证码的页面

<asp:Image Runat="server" ID="ImageCheck" ImageUrl="ValidateCode.aspx"></asp:Image>
 

把最近碰到的 能够用的验证码 都放出来,作个记录
1.GSC_WebControlLibrary 这是在网上找到的一个控件,非常好用。但是效果不是特别好(见下图。
)虽然容易使用,所有的属性都可以像控件一样设置,但是可用性不太高。用户不能自定义,而且看起来这个验证码效果不太好。
效果:

2.用一个页面生成图片,另一个页面调用,验证码存入cookie,调用时取cookie对比验证.这个用户就可以按自己的喜好更改效果和验证码的长度了 (:

效果如图:


代码如下:
CheckCode.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.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public partial class Tools_CheckCode : 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));

        
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.Next(image.Height);
                
int y2 = random.Next(image.Height);

                g.DrawLine(
new Pen(Color.GreenYellow), x1, y1, x2, y2);
            }


            Font font 
= new System.Drawing.Font("Verdana"12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush 
= new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(00, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2ftrue);
            g.DrawString(checkCode, font, brush, 
22);

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

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }


            
//画图片的边框线
            g.DrawRectangle(new Pen(Color.Red), 00, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType 
= "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }

        
finally
        
{
            g.Dispose();
            image.Dispose();
        }

    }



}


然后在需要使用的页面引用:
UseCheckCode.aspx
<img src="Tools/CheckCode.aspx" alt="验证码" style=" 60px; height: 24px" />

3.用web handler生成图片。这个其实和前面的意思大致差不多,调用方法也基本和2一样,不同的是,他的验证码是存入Session的。供学习参考。

效果图如下:


ValidateImageHandler.ashx
%@ WebHandler Language="C#" Class="ValidateImageHandler" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

/// <summary>
/// ValidateImageHandler 生成网站验证码功能
/// </summary>

public class ValidateImageHandler : IHttpHandler, IRequiresSessionState
{
    
int intLength = 5;               //长度
    string strIdentify = "Identify"//随机字串存储键值,以便存储到Session中
    public ValidateImageHandler()
    
{        
    }


    
/// <summary>
    
///  生成验证图片核心代码
    
/// </summary>
    
/// <param name="hc"></param>

    public void ProcessRequest(HttpContext hc)
    
{
        
//设置输出流图片格式
        hc.Response.ContentType = "image/gif";
        
        Bitmap b 
= new Bitmap(20060);
        Graphics g 
= Graphics.FromImage(b);
        g.FillRectangle(
new SolidBrush(Color.YellowGreen), 0020060);
        Font font 
= new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
        Random r 
= new Random();

        
//合法随机显示字符列表
        string strLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder s 
= new StringBuilder();
        
        
//将随机生成的字符串绘制到图片上
        for (int i = 0; i < intLength; i++)
        
{
            s.Append(strLetters.Substring(r.Next(
0, strLetters.Length - 1), 1));
            g.DrawString(s[s.Length 
- 1].ToString(), font, new SolidBrush(Color.Blue), i * 38, r.Next(015));
        }


        
//生成干扰线条
        Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
        
for (int i = 0; i < 10; i++)
        
{
            g.DrawLine(pen, 
new Point(r.Next(0199), r.Next(059)), new Point(r.Next(0199), r.Next(059)));
        }

        b.Save(hc.Response.OutputStream, ImageFormat.Gif);
        hc.Session[strIdentify] 
= s.ToString(); //先保存在Session中,验证与用户输入是否一致
        hc.Response.End();
   
    }

    
    
/// <summary>
    
/// 表示此类实例是否可以被多个请求共用(重用可以提高性能)
    
/// </summary>

    public bool IsReusable
    
{
        
get
        
{
            
return true;
        }

    }

}

原文地址:https://www.cnblogs.com/yongheng178/p/1262338.html