首頁  >  文章  >  後端開發  >  利用ashx產生圖形驗證碼實例教程

利用ashx產生圖形驗證碼實例教程

巴扎黑
巴扎黑原創
2017-08-06 11:35:371948瀏覽

這篇文章主要介紹了asp.net使用ashx產生圖形驗證碼的方法,結合實例形式分析了asp.net產生圖形驗證碼的步驟、實作方法與相關注意事項,需要的朋友可以參考下

本文實例講述了asp.net使用ashx產生圖形驗證碼的方法。分享給大家供大家參考,具體如下:

驗證碼的好處不用我多說,你們都懂的。我在網路上看到有人把驗證碼直接寫在aspx頁面裡,也就是說這種方式請求驗證碼等於請求一個頁面,這樣做很不科學。如下圖


<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產生圖形驗證碼


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.在頁面上顯示驗證碼,因為我們產生的是圖形,所以可以直接寫在79d7c95122630a3791db16c5259dc98d標籤裡,我們只要寫段簡單的腳本就可以點擊滑鼠切換驗證碼了


<%@ 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>

說了半天,該是時候看看生成的驗證碼長什麼樣子了

以上是利用ashx產生圖形驗證碼實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn