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

C#验证码的创建与使用示例

程序员文章站 2022-05-09 08:16:39
本文实例讲述了c#验证码的创建与使用方法。分享给大家供大家参考,具体如下: 1、c#创建验证码 ① 创建获取验证码页面(validatecode.aspx)...

本文实例讲述了c#验证码的创建与使用方法。分享给大家供大家参考,具体如下:

1、c#创建验证码

① 创建获取验证码页面(validatecode.aspx)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>获取验证码</title>
</head>
<body>
  <form id="form1" runat="server">
    <div>获取验证码</div>
  </form>
</body>
</html>

② 编写获取验证码代码(validatecode.aspx.cs)

/// <summary>
/// 验证码类型(0-字母数字混合,1-数字,2-字母)
/// </summary>
private string validatecodetype = "0";
/// <summary>
/// 验证码字符个数
/// </summary>
private int validatecodecount = 4;
/// <summary>
/// 验证码的字符集,去掉了一些容易混淆的字符
/// </summary>
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'w', 'x', 'y' };
protected void page_load(object sender, eventargs e)
{
  //取消缓存
  response.bufferoutput = true;
  response.cache.setexpires(datetime.now.addmilliseconds(-1));
  response.cache.setcacheability(system.web.httpcacheability.nocache);
  response.appendheader("pragma", "no-cache");
  //获取设置参数
  if (!string.isnullorempty(request.querystring["validatecodetype"]))
  {
    validatecodetype = request.querystring["validatecodetype"];
  }
  if (!string.isnullorempty(request.querystring["validatecodecount"]))
  {
    int.tryparse(request.querystring["validatecodecount"], out validatecodecount);
  }
  //生成验证码
  this.createcheckcodeimage(generatecheckcode());
}
private string generatecheckcode()
{
  char code ;
  string checkcode = string.empty;
  system.random random = new random();
  for (int i = 0; i < validatecodecount; i++)
  {
    code = character[random.next(character.length)];
    // 要求全为数字或字母
    if (validatecodetype == "1")
    {
      if ((int)code < 48 || (int)code > 57)
      {
        i--;
        continue;
      }
    }
    else if (validatecodetype == "2")
    {
      if ((int)code < 65 || (int)code > 90)
      {
        i--;
        continue;
      }
    }
    checkcode += code;
  }
  response.cookies.add(new system.web.httpcookie("checkcode", checkcode));
  this.session["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*15.0+40)), 23);
  system.drawing.graphics g = system.drawing.graphics.fromimage(image);
  try
  {
    //生成随机生成器
    random random = new random();
    //清空图片背景色
    g.clear(system.drawing.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 system.drawing.pen(system.drawing.color.silver), x1, y1, x2, y2);
    }
    system.drawing.font font = new system.drawing.font("arial", 14, (system.drawing.fontstyle.bold | system.drawing.fontstyle.italic));
    system.drawing.drawing2d.lineargradientbrush brush = new system.drawing.drawing2d.lineargradientbrush(new system.drawing.rectangle(0, 0, image.width, image.height), system.drawing.color.blue, system.drawing.color.darkred, 1.2f, true);
    int cyspace = 16;
    for (int i = 0; i < validatecodecount; i++)
    {
      g.drawstring(checkcode.substring(i, 1), font, brush, (i + 1) * cyspace, 1);
    }
    //画图片的前景噪音点
    for (int i = 0; i < 100; i++)
    {
      int x = random.next(image.width);
      int y = random.next(image.height);
      image.setpixel(x, y, system.drawing.color.fromargb(random.next()));
    }
    //画图片的边框线
    g.drawrectangle(new system.drawing.pen(system.drawing.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、验证码的使用

① 验证码的前段显示代码

复制代码 代码如下:
<img src="/validatecode.aspx?validatecodetype=1&0.011150883024061309" onclick="this.src='/validatecode.aspx?validatecodetype=1&'+math.random();" id="imgvalidatecode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">

② 创建验证码测试页面(validatetest.aspx)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>验证码测试</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input runat="server" id="txtvalidate" />
    <img src="/validatecode.aspx?validatecodetype=1&0.011150883024061309" onclick="this.src='/validatecode.aspx?validatecodetype=1&'+math.random();" id="imgvalidatecode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
    <asp:button runat="server" id="btnval" text="提交" onclick="btnval_click" />
  </div>
  </form>
</body>
</html>

③ 编写验证码测试的提交代码(validatetest.aspx.cs)

protected void btnval_click(object sender, eventargs e)
{
  bool result = false;  //验证结果
  string usercode = this.txtvalidate.value; //获取用户输入的验证码
  if (string.isnullorempty(usercode))
  {
    //请输入验证码
    return;
  }
  string validcode = this.session["checkcode"] as string; //获取系统生成的验证码
  if (!string.isnullorempty(validcode))
  {
    if (usercode.tolower() == validcode.tolower())
    {
      //验证成功
      result = true;
    }
    else
    {
      //验证失败
      result = false;
    }
  }
}

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#图片操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。