欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET实现的生成验证码功能示例【附demo源码】

程序员文章站 2023-02-15 19:47:53
本文实例讲述了asp.net实现的生成验证码功能。分享给大家供大家参考,具体如下: 生成验证码原理:产生随机字符,并将字符生成为图片,同时储存到session里去,然后验...

本文实例讲述了asp.net实现的生成验证码功能。分享给大家供大家参考,具体如下:

生成验证码原理:产生随机字符,并将字符生成为图片,同时储存到session里去,然后验证用户输入的内容是否与session中的验证码相符即可。

效果图:用户可以点击切换验证码信息。

ASP.NET实现的生成验证码功能示例【附demo源码】

一般处理程序:checkcodehandler.cs

<%@ webhandler language="c#" class="checkcodehandler" %>
using system;
using system.web;
using system.text;
using system.drawing;
using system.web.sessionstate;
public class checkcodehandler : ihttphandler,irequiressessionstate
{
  //产生验证码的字符集
  public string charcode = "2,3,4,5,6,8,9,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y";
  public void processrequest (httpcontext context) {
    string validatecode = createrandomcode(4);
    context.session["validatecode"] = validatecode;//将验证码保存到session中
    createcodeimage(validatecode, context);
  }
  public bool isreusable {
    get {
      return false;
    }
  }
  /// <summary>
  /// 生成验证码
  /// </summary>
  /// <param name="n">验证码个数</param>
  /// <returns>验证码字符串</returns>
  public string createrandomcode(int n)
  {
    string[] chararray = charcode.split(',');//将字符串转换为字符数组
    string randomcode = "";
    int temp = -1;
    random rand = new random();
    for (int i = 0; i < n; i++)
    {
      if (temp != -1)
      {
        rand = new random(i * temp * ((int)datetime.now.ticks));
      }
      int t = rand.next(chararray.length - 1);
      if (temp != -1 && temp == t)
      {
        return createrandomcode(n);
      }
      temp = t;
      randomcode += chararray[t];
    }
    return randomcode;
  }
  public void createcodeimage(string checkcode, httpcontext context)
  {
    int iwidth = (int)(checkcode.length * 13);
    system.drawing.bitmap image = new system.drawing.bitmap(iwidth, 20);
    graphics g = graphics.fromimage(image);
    font f = new system.drawing.font("arial", 12, (system.drawing.fontstyle.italic | system.drawing.fontstyle.bold));
    // 前景色
    brush b = new system.drawing.solidbrush(color.black);
    // 背景色
    g.clear(color.white);
    // 填充文字
    g.drawstring(checkcode, f, b, 0, 1);
    // 随机线条
    pen linepen = new pen(color.gray, 0);
    random rand = new random();
    for (int i = 0; i < 5; i++)
    {
      int x1 = rand.next(image.width);
      int y1 = rand.next(image.height);
      int x2 = rand.next(image.width);
      int y2 = rand.next(image.height);
      g.drawline(linepen, x1, y1, x2, y2);
    }
    // 随机点
    for (int i = 0; i < 30; i++)
    {
      int x = rand.next(image.width);
      int y = rand.next(image.height);
      image.setpixel(x, y, color.gray);
    }
    // 边框
    g.drawrectangle(new pen(color.gray), 0, 0, image.width - 1, image.height - 1);
    // 输出图片
    system.io.memorystream ms = new system.io.memorystream();
    image.save(ms, system.drawing.imaging.imageformat.jpeg);
    context.response.clearcontent();
    context.response.contenttype = "image/jpeg";
    context.response.binarywrite(ms.toarray());
    g.dispose();
    image.dispose();
  }
}

封装成类库:validatenumber.cs

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.drawing;
using system.web.ui;
using system.drawing.drawing2d;
using system.io;
using system.drawing.imaging;
/// <summary>
///validatenumber 生成验证码
/// </summary>
public class validatenumber
{
  //产生验证码的字符集 (易混淆的字符去掉)
  private string charcode = "2,3,4,5,6,8,9,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y";
  /// <summary>
  /// 验证码的最大长度
  /// </summary>
  public int maxlength
  {
    get { return 10; }
  }
  /// <summary>
  /// 验证码的最小长度
  /// </summary>
  public int minlength
  {
    get { return 1; }
  }
  /// <summary>
  /// 生成验证码
  /// </summary>
  /// <param name="length">指定验证码的长度</param>
  /// <returns></returns>
  public string createvalidatenumber(int length)
  {
    string[] chararray = charcode.split(',');//将字符串转换为字符数组
    string randomcode = "";
    int temp = -1;
    random rand = new random();
    for (int i = 0; i < length; i++)
    {
      if (temp != -1)
      {
        rand = new random(i * temp * ((int)datetime.now.ticks));
      }
      int t = rand.next(chararray.length - 1);
      if (temp != -1 && temp == t)
      {
        return createvalidatenumber(length);
      }
      temp = t;
      randomcode += chararray[t];
    }
    return randomcode;
  }
  /// <summary>
  /// 创建验证码的图片
  /// </summary>
  /// <param name="context">context对象</param>
  /// <param name="validatenum">验证码</param>
  public void createvalidategraphic(httpcontext context,string validatenum)
  {
    int iwidth = (int)(validatenum.length * 14);
    bitmap image = new bitmap(iwidth, 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 font("arial", 12, (fontstyle.bold | fontstyle.italic));
      lineargradientbrush brush = new lineargradientbrush(new rectangle(0, 0, image.width, image.height),
       color.blue, color.darkred, 1.2f, true);
      g.drawstring(validatenum, font, brush, 3, 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);
      //保存图片数据
      memorystream stream = new memorystream();
      image.save(stream, imageformat.jpeg);
      //输出图片
      context.response.clear();
      context.response.contenttype = "image/jpeg";
      context.response.binarywrite(stream.toarray());
    }
    finally
    {
      g.dispose();
      image.dispose();
    }
  }
  /// <summary>
  /// 得到验证码图片的长度
  /// </summary>
  /// <param name="validatenumlength">验证码的长度</param>
  /// <returns></returns>
  public static int getimagewidth(int validatenumlength)
  {
    return (int)(validatenumlength * 14);
  }
  /// <summary>
  /// 得到验证码图片的高度
  /// </summary>
  /// <returns></returns>
  public static double getimageheight()
  {
    return 22;
  }
}

附:完整实例代码点击此处。

更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net操作json技巧总结》、《asp.net字符串操作技巧汇总》、《asp.net操作xml技巧总结》、《asp.net文件操作技巧汇总》、《asp.net ajax技巧总结专题》及《asp.net缓存操作技巧总结》。

希望本文所述对大家asp.net程序设计有所帮助。