当前位置: 移动技术网 > IT编程>开发语言>.net > 详解ASP.NET验证码的生成方法

详解ASP.NET验证码的生成方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

剪草机型号,bugu,黄坤明老婆邱萍

一般验证码的生成方法都是相同的,主要的步骤都有两步

第一步:随机出一系统验证码的数字或字母,顺便把随机生成的数字或字母写入cookies 或者 session。

第二步:用第一步随机出来的数字或字母来合成图片。

可以看出来验证码的复杂度主要是第二步来完成,你可以根据自己所要的复杂度来设定。

我们一起来看看:

 第一步:随机生成数字或字母的方法

/// <summary>
  /// 生成验证码的随机数
  /// </summary>
  /// <returns>返回五位随机数</returns>
  private string generatecheckcode()
  {
    int number;
    char code;
    string checkcode = string.empty;

    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));//写入cookis
    session["checkcode"] = checkcode; //写入session,可以任意选一下
    return checkcode;
  }

第二步:生成图片

/// <summary>
  /// 生成验证码图片
  /// </summary>
  /// <param name="checkcode"></param>
  private void createcheckcodeimage(string checkcode)
  {
    if (checkcode == null || checkcode.trim() == string.empty)
      return;

    bitmap image = new 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));
      lineargradientbrush brush = new 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);

      memorystream ms = new memorystream();
      image.save(ms, system.drawing.imaging.imageformat.gif);
      response.clearcontent();
      response.contenttype = "image/gif";
      response.binarywrite(ms.toarray());
    }
    finally
    {//释放对象资源
      g.dispose();
      image.dispose();
    }

*完整程序

先在vs2005里面的项目里面添加一个 checkcode.aspx 文件,在checkcode.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.io;
using system.drawing.drawing2d;

public partial class checkcode : system.web.ui.page
{
  protected void page_load(object sender, eventargs e)
  {
    createcheckcodeimage(generatecheckcode());//调用下面两个方法;
  }

  /// <summary>
  /// 生成验证码的随机数
  /// </summary>
  /// <returns>返回五位随机数</returns>
  private string generatecheckcode()
  {
    int number;
    char code;
    string checkcode = string.empty;

    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));//写入cookis
    session["checkcode"] = checkcode; //写入session,可以任意选一下
    return checkcode;
  }


  /// <summary>
  /// 生成验证码图片
  /// </summary>
  /// <param name="checkcode"></param>
  private void createcheckcodeimage(string checkcode)
  {
    if (checkcode == null || checkcode.trim() == string.empty)
      return;

    bitmap image = new 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));
      lineargradientbrush brush = new 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);

      memorystream ms = new memorystream();
      image.save(ms, system.drawing.imaging.imageformat.gif);
      response.clearcontent();
      response.contenttype = "image/gif";
      response.binarywrite(ms.toarray());
    }
    finally
    {//释放对象资源
      g.dispose();
      image.dispose();
    }
  }

}

上面生成验证码的页面都做好了,我们来调用看看:

在你需要用到验证码的地方加了image控件

<asp:image id="image1" runat="server" imageurl="~/checkcode.aspx" />

这样验证码就会显示到image控件上面了!

显示弄好了,当然我们要判断一下用户的输入是否正确!

只要我们取得用户输入的值跟cookis或者session对比就ok了

取cookies的值 request.cookies["checkcode"].value

取session的值 session["checkcode"].tostring()    (最好先判断session是否空)

如果不要区分大小写的话,就把用户输入的值和cookies或session的值都转成大写或都小写 

附用法

protected void button1_click(object sender, eventargs e)
  {
    if (request.cookies["checkcode"].value == textbox1.text.trim().tostring())
    {
      response.write("cookies is right");
    }
    else
    {
      response.write("cookies is wrong");
    }

    if (session["checkcode"] != null)
    {
      if (session["checkcode"].tostring().toupper() == textbox1.text.trim().tostring().toupper())
        //这样写可以不能区分大小写
      {
        response.write("session is right");

      }
      else
      {
        response.write("session is wrong");
      }
    }
  }

以上就是本文的全部内容,教大家如何制作asp.net验证码,希望大家喜欢。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网