asp.net利用ashx实现验证码功能详解


本文摘自PHP中文网,作者巴扎黑,侵删。

这篇文章主要介绍了asp.net使用ashx生成图形验证码的方法,结合实例形式分析了asp.net生成图形验证码的步骤、实现方法与相关注意事项,需要的朋友可以参考下

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

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


1

2

3

4

5

6

7

8

<form id="form1" runat="server">

  <p>

    <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" />

  </p>

</form>

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

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

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

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/>标签里,我们只要写段简单的脚本就可以点击鼠标切换验证码了


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<%@ 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利用ashx实现验证码功能详解

asp.net中md5加密码的代码详解

aspx是什么文件?

asp.net操作日期常用代码

介绍asp.net的几种分页方式

asp.net下的中文分词检索工具分享

asp.net》数据的绑定―repeater图文详解

asp.net使用x509certificate2出现的一些问题的解决方法分享(图)

asp.net mvc 遇到json循环调用的问题应该怎么解决?

asp.net之actionfilter过滤器

更多相关阅读请进入《asp.net》频道 >>




打赏

取消

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

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...