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

asp.net使用ashx生成图形验证码的方法示例

程序员文章站 2023-02-15 18:50:13
本文实例讲述了asp.net使用ashx生成图形验证码的方法。分享给大家供大家参考,具体如下: 验证码的好处不用我多说,你们都懂的。我在网上看到有人把验证码直接写在asp...

本文实例讲述了asp.net使用ashx生成图形验证码的方法。分享给大家供大家参考,具体如下:

验证码的好处不用我多说,你们都懂的。我在网上看到有人把验证码直接写在aspx页面里,也就是说这种方式请求验证码等于请求一个页面,这样做很不科学。如下所示

<form id="form1" runat="server">
  <div>
    <asp:image id="image1" runat="server" imageurl="default.aspx" />
    <br />
    <asp:textbox id="textbox1" runat="server"></asp:textbox>
    <asp:button id="button1" runat="server" onclick="button1_click" text="button" />
  </div>
</form>

这个代码看着就觉得写代码的人比较欠揍,代码写成这样子着实郁闷。验证吗也不写点script做下切换。

下面我介绍一种方式来实现这样的功能

1. 写个ashx生成图形验证码

using system;
using system.collections;
using system.data;
using system.linq;
using system.web;
using system.web.services;
using system.web.services.protocols;
using system.xml.linq;
using system.web.sessionstate;
using system.drawing;
namespace usechecknum.ashx
{
  /// <summary>
  /// $codebehindclassname$ 的摘要说明
  /// </summary>
  [webservice(namespace = "http://tempuri.org/")]
  [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
  public class docreatenum : ihttphandler,irequiressessionstate
  {
    public void processrequest(httpcontext context)
    {
      context.response.contenttype = "text/html";
      string checkcode = getvalidation(5); // 产生5位随机验证码字符
      context.session["code"] = checkcode; //将字符串保存到session中,以便需要时进行验证
      system.drawing.bitmap image = new system.drawing.bitmap(70, 22);
      graphics g = graphics.fromimage(image);
      try
      {
        //生成随机生成器
        random random = new random();
        //清空图片背景色
        g.clear(color.white);
        // 画图片的背景噪音线
        int i;
        for (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.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);
        //画图片的前景噪音点
        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);
        context.response.clearcontent();
        context.response.contenttype = "image/gif";
        context.response.binarywrite(ms.toarray());
      }
      finally
      {
        g.dispose();
        image.dispose();
      }
    }
    public string getvalidation(int num)
    {
      string str = "0123456789abcdefghijklmnopqrstuvwxyz"; //"或者写汉字也行"
      string validatecode = "";
      random rd = new random();
      for (int i = 0; i < num; i++)
      {
        validatecode += str.substring(rd.next(0, str.length), 1);
      }
      return validatecode;
    }
    public bool isreusable
    {
      get
      {
        return false;
      }
    }
  }
}

2. 在页面上显示验证码,因为我们生成的是图形,所以可以直接写在<img/>标签里,我们只要写段简单的脚本就可以点击鼠标切换验证码了

<%@ page language="c#" autoeventwireup="true" codebehind="index.aspx.cs" inherits="usechecknum._default" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>验证码的使用</title>
</head>
<script language="javascript" type="text/javascript">
  function changecode() {
    var imgnode = document.getelementbyid("vimg");
    imgnode.src = "ashx/docreatenum.ashx?t=" + (new date()).valueof(); // 这里加个时间的参数是为了防止浏览器缓存的问题
  }
  </script>
<body>
  <form id="form1" runat="server">
   请输入验证码:<input type="text" name="checknum"/><img src="ashx/docreatenum.ashx" id="vimg" onclick="changecode()" />
  </form>
</body>
</html>

说了半天,该是时候看看生成的验证码长什么样了

asp.net使用ashx生成图形验证码的方法示例

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

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