ASP.NET驗證碼(3種)

來源:互聯網
上載者:User
ASP.NET驗證碼(3種)
1.GSC_WebControlLibrary 這是在網上找到的一個控制項,非常好用。但是效果不是特別好(見。
)雖然容易使用,所有的屬性都可以像控制項一樣設定,但是可用性不太高。使用者不能自訂,而且看起來這個驗證碼效果不太好。
效果:

2.用一個頁面產生圖片,另一個頁面調用,驗證碼存入cookie,調用時取cookie對比驗證.這個使用者就可以按自己的喜好更改效果和驗證碼的長度了 (:

效果

代碼如下:
CheckCode.aspx

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public partial class Tools_CheckCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.CreateCheckCodeImage(GenerateCheckCode());

    }

    private string GenerateCheckCode()
    {
        int number;
        char code;
        string checkCode = String.Empty;

        System.Random random = new Random();

        for (int i = 0; i < 5; i++)
        {
            number = random.Next();

            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                code = (char)('A' + (char)(number % 26));

            checkCode += code.ToString();
        }

        Response.Cookies.Add(new HttpCookie("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 * 12.5)), 22);
        Graphics g = Graphics.FromImage(image);

        try
        {
            //產生隨機產生器
            Random random = new Random();

            //清空圖片背景色
            g.Clear(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 Pen(Color.GreenYellow), x1, y1, x2, y2);
            }

            Font font = new System.Drawing.Font("Verdana", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            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);

            //畫圖片的前景噪音點
            for (int i = 0; i < 80; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //畫圖片的邊框線
            g.DrawRectangle(new Pen(Color.Red), 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();
        }
    }

}

然後在需要使用的頁面引用:
UseCheckCode.aspx
<img src="Tools/CheckCode.aspx" alt="驗證碼" style="width: 60px; height: 24px" />
3.用web handler產生圖片。這個其實和前面的意思大致差不多,調用方法也基本和2一樣,不同的是,他的驗證碼是存入Session的。供學習參考。

如下:

ValidateImageHandler.ashx
%@ WebHandler Language="C#" Class="ValidateImageHandler" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

/**//// <summary>
/// ValidateImageHandler 產生網站驗證碼功能
/// </summary>
public class ValidateImageHandler : IHttpHandler, IRequiresSessionState
{
    int intLength = 5;               //長度
    string strIdentify = "Identify"; //隨機字串儲存索引值,以便儲存到Session中
    public ValidateImageHandler()
    {       
    }

    /**//// <summary>
    /// 產生驗證圖片核心代碼
    /// </summary>
    /// <param name="hc"></param>
    public void ProcessRequest(HttpContext hc)
    {
        //設定輸出資料流圖片格式
        hc.Response.ContentType = "image/gif";
       
        Bitmap b = new Bitmap(200, 60);
        Graphics g = Graphics.FromImage(b);
        g.FillRectangle(new SolidBrush(Color.YellowGreen), 0, 0, 200, 60);
        Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
        Random r = new Random();

        //合法隨機顯示字元列表
        string strLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder s = new StringBuilder();
       
        //將隨機產生的字串繪製到圖片上
        for (int i = 0; i < intLength; i++)
        {
            s.Append(strLetters.Substring(r.Next(0, strLetters.Length - 1), 1));
            g.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(Color.Blue), i * 38, r.Next(0, 15));
        }

        //產生幹擾線條
        Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
        for (int i = 0; i < 10; i++)
        {
            g.DrawLine(pen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
        }
        b.Save(hc.Response.OutputStream, ImageFormat.Gif);
        hc.Session[strIdentify] = s.ToString(); //先儲存在Session中,驗證與使用者輸入是否一致
        hc.Response.End();
  
    }
   
    /**//// <summary>
    /// 表示此類執行個體是否可以被多個請求共用(重用可以提高效能)
    /// </summary>
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.