ASP.NET实现图形验证码功能

2024-04-16 0 735
目录
  • 一、实现思路
  • 二、编写前端代码
    • 1、编写HTML代码
    • 2、创建JavaScript函数
  • 三、编写后端代码
    • 1、创建输出图形验证码的接口
    • 2、创建验证码生成方法
    • 3、 绘制验证码图片
      • ① 配置验证码参数
      • ② 生成验证码字符串
      • ③ 构建验证码背景
      • ④ 画噪音线
      • ⑤ 画验证码
      • ⑥ 画噪音点
      • ⑦ 画边框线
      • ⑧ 将验证码图像保存到内存流
      • ⑨ 将验证码保存到Session中
      • ⑩ 输出图像到客户端
    • 4、完整后端代码
    • 四、测试效果

      ASP.NET 实现图形验证码能够增强网站安全性,防止机器人攻击。通过生成随机验证码并将其绘制成图像,用户在输入验证码时增加了人机交互的难度。本文介绍了如何使用 C# 和 ASP.NET 创建一个简单而有效的图形验证码系统,包括生成随机验证码、绘制验证码图像以及将图像输出到客户端等步骤。这种验证码系统对于保护网站免受恶意攻击和机器人恶意行为具有重要意义。

      一、实现思路

      我们需要实现一个防爬虫的可以动态刷新的随机验证码图片。比如下面这种:

      ASP.NET实现图形验证码功能

      关键点:

      • 动态:每次打开页面验证码是变化的,并且验证码在一些事件下会自发刷新成新的验证码,比如在点击、输入错误、页面停靠超时等事件触发时,验证码自动刷新。
      • 随机:里面的数字和字母是随机的,是一种强密码,不容易被暴力破解。
      • 防爬:防止爬虫通过一些AI识别直接通过,我们需要增加图片的复杂度,例如添加一些干扰性的图案,包括但不限于噪音线、噪点等。

      验证码生成成功后,我们还需要将验证码保存到 Session 中,以便后续验证。

      二、编写前端代码

      思路已经明确,下面,我们来构建图形验证码的前端代码。前端代码包含 HTML 和 JavaScript 代码。

      1、编写HTML代码

      HTML代码包含一个简单的验证码输入框和刷新图片按钮的用户界面:

      <div class=\”checkcode\”>
      <input type=\”text\” runat=\”server\” id=\”VercodeText\” placeholder=\”验证码\” maxlength=\”4\”>
      <img onclick=\”changepic(this)\” src=\”/handlers/VerCode.ashx\” />
      </div>

      • <div class="checkcode">:创建一个包含验证码元素的 div 容器,用于样式控制。
      • <input type="text" runat="server" id="VercodeText" placeholder="验证码" maxlength="4">:添加一个文本输入框,用于用户输入验证码。设置了ID为 "VercodeText",最大长度为4,同时提供了占位符 "验证码"。
      • <img οnclick="changepic(this)" src="/handlers/VerCode.ashx" />:插入一个图片元素,其 src 属性指向验证码处理器 VerCode.ashx。当用户点击该图片时,触发JavaScript函数 changepic 进行验证码图像的刷新。

      通过这样的HTML结构,用户可以在输入框中输入验证码,并通过点击图片刷新验证码图像,提供了一种交互式的验证码体验。

      2、创建JavaScript函数

      创建changepic 函数方法:

      function changepic(obj) {
      var timestamp = (new Date().getTime()) / 1000;
      $(obj).attr(\’src\’, \’VerCode.ashx?tims=\’ + timestamp);
      }

      changepic 函数用于刷新验证码图片,通过在 URL 中添加时间戳的方式,确保每次请求都是唯一的,避免浏览器缓存。

      三、编写后端代码

      后端代码我们采用C#实现。

      1、创建输出图形验证码的接口

      创建C#验证码处理器 VerCode.ashx:

      using CarRental.Common;
      using System;
      using System.Drawing;
      using System.IO;
      using System.Web;
      namespace Handlers
      {
      public class VerCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
      {
      public void ProcessRequest(HttpContext context)
      {
      }
      public bool IsReusable
      {
      get
      {
      return false;
      }
      }
      }
      }

      VerCode 类实现了 IHttpHandler 接口,用于处理 HTTP 请求。

      2、创建验证码生成方法

      /// <summary>
      /// 随机构建验证码方法
      /// </summary>
      /// <returns>返回验证码字符串</returns>
      public string CreateCode()
      {
      char code;
      string checkCode = string.Empty;
      Random rd = new Random();
      for (int i = 0; i < 4; i++)
      {
      int num = rd.Next();
      int _temp;
      if (num % 2 == 0)
      {
      _temp = (\’0\’ + (char)(num % 10));
      if (_temp == 48 || _temp == 49)
      {
      _temp += rd.Next(2, 9);
      }
      }
      else
      {
      _temp = (\’A\’ + (char)(num % 10));
      if (rd.Next(0, 2) == 0)
      {
      _temp = (char)(_temp + 32);
      }
      if (_temp == 66 || _temp == 73 || _temp == 79 || _temp == 108 || _temp == 111)
      {
      _temp++;
      }
      }
      code = (char)_temp;
      checkCode += code;
      }
      return checkCode;
      }

      CreateCode 方法用于生成随机验证码,包含数字和字母,并进行了一些特殊字符的处理,以增加验证码的复杂性。

      3、 绘制验证码图片

      ① 配置验证码参数

      我们先定义验证码图像的宽度、高度、字体大小以及用于生成随机数的 Random 对象。

      int codeWeight = 80;
      int codeHeight = 22;
      int fontSize = 16;
      Random rd = new Random();

      ② 生成验证码字符串

      这一步很简单,我们直接调用之前写好的 CreateCode 方法。

      string checkCode = CreateCode();

      ③ 构建验证码背景

      创建一个位图对象,并在其上创建图形对象,然后用白色填充图像背景。

      Bitmap image = new Bitmap(codeWeight, codeHeight);
      Graphics g = Graphics.FromImage(image);
      g.Clear(Color.White);

      ④ 画噪音线

      在图像上绘制两条随机颜色的噪音线,增加验证码的复杂性。

      for (int i = 0; i < 2; i++)
      {
      int x1 = rd.Next(image.Width);
      int x2 = rd.Next(image.Width);
      int y1 = rd.Next(image.Height);
      int y2 = rd.Next(image.Height);
      g.DrawLine(new Pen(color[rd.Next(color.Length)]), new Point(x1, y1), new Point(x2, y2));
      }

      ⑤ 画验证码

      使用循环逐个绘制验证码字符串中的字符,每个字符使用随机颜色和字体。

      for (int i = 0; i < checkCode.Length; i++)
      {
      Color clr = color[rd.Next(color.Length)];
      Font ft = new Font(font[rd.Next(font.Length)], fontSize);
      g.DrawString(checkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 + 2, 0);
      }

      ⑥ 画噪音点

      在图像上绘制100个随机颜色的噪音点,增加验证码的随机性。

      for (int i = 0; i < 100; i++)
      {
      int x = rd.Next(image.Width);
      int y = rd.Next(image.Height);
      image.SetPixel(x, y, Color.FromArgb(rd.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);

      ⑨ 将验证码保存到Session中

      将生成的验证码字符串保存到Session中,以便后续验证。

      context.Session[ConstantValues.VerCodeSessionName] = checkCode;

      ⑩ 输出图像到客户端

      配置HTTP响应,将验证码图像输出到客户端。

      context.Response.ContentType = \”Image/Gif\”;
      context.Response.ClearContent();
      context.Response.BinaryWrite(ms.ToArray());

      最后,别忘记释放图像和图形资源,防止内存泄漏。

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

      4、完整后端代码

      完整的VerCode.cs 代码如下:

      using TestMoudle.Common;
      using System;
      using System.Drawing;
      using System.IO;
      using System.Web;
      namespace Handlers
      {
      public class VerCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
      {
      public void ProcessRequest(HttpContext context)
      {
      int codeWeight = 80;
      int codeHeight = 22;
      int fontSize = 16;
      Random rd = new Random();
      string checkCode = CreateCode(); //构建验证码字符串
      Bitmap image = new Bitmap(codeWeight, codeHeight); //构建画图
      Graphics g = Graphics.FromImage(image); //构建画布
      g.Clear(Color.White); //清空背景色
      Color[] color = new Color[] { Color.Red, Color.Black, Color.Green, Color.Blue };
      string[] font = new string[] { \”宋体\”, \”黑体\”, \”楷体\” };
      //画噪音线
      for (int i = 0; i < 2; i++)
      {
      int x1 = rd.Next(image.Width);
      int x2 = rd.Next(image.Width);
      int y1 = rd.Next(image.Height);
      int y2 = rd.Next(image.Height);
      g.DrawLine(new Pen(color[rd.Next(color.Length)]), new Point(x1, y1), new Point(x2, y2));
      }
      //画验证码
      for (int i = 0; i < checkCode.Length; i++)
      {
      Color clr = color[rd.Next(color.Length)];
      Font ft = new Font(font[rd.Next(font.Length)], fontSize);
      g.DrawString(checkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 + 2, 0);
      }
      //画噪音点
      for (int i = 0; i < 100; i++)
      {
      int x = rd.Next(image.Width);
      int y = rd.Next(image.Height);
      image.SetPixel(x, y, Color.FromArgb(rd.Next()));
      }
      //画边框线
      g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width – 1, image.Height – 1);
      MemoryStream ms = new MemoryStream();
      try
      {
      image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
      context.Session[ConstantValues.VerCodeSessionName] = checkCode; //将验证码保存到Session中
      context.Response.ContentType = \”Image/Gif\”;
      context.Response.ClearContent();
      context.Response.BinaryWrite(ms.ToArray());
      }
      finally
      {
      image.Dispose();
      g.Dispose();
      }
      }
      public bool IsReusable
      {
      get
      {
      return false;
      }
      }
      }
      }

      四、测试效果

      我们运行项目,可以看到验证码图像顺利生成了,并且点击可以刷新图片内容。

      ASP.NET实现图形验证码功能

      到此这篇关于ASP.NET实现图形验证码的文章就介绍到这了,更多相关ASP.NET图形验证码内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

      您可能感兴趣的文章:

      • asp.net使用ashx生成图形验证码的方法示例
      • ASP.NET中画图形验证码的实现代码
      • ASP.NET生成图形验证码的方法详解
      • asp.net生成字母和数字混合图形验证码

      收藏 (0) 打赏

      感谢您的支持,我会继续努力的!

      打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
      点赞 (0)

      悠久资源 ASP.NET ASP.NET实现图形验证码功能 https://www.u-9.cn/biancheng/aspnet/186075.html

      常见问题

      相关文章

      发表评论
      暂无评论
      官方客服团队

      为您解决烦忧 - 24小时在线 专业服务