首頁 後端開發 C#.Net教程 詳解ASP.NET驗證碼的產生方法

詳解ASP.NET驗證碼的產生方法

Jan 13, 2017 pm 02:57 PM

一般驗證碼的產生方法都是相同的,主要的步驟都有兩步

第一步:隨機出一系統驗證碼的數字或字母,順便把隨機生成的數字或字母寫入Cookies 或者 Session。

第二步:用第一步隨機出來的數字或字母來合成圖片。

可以看出來驗證碼的複雜度主要是第二步來完成,你可以根據自己所要的複雜度來設定。

我們一起來看看:

 第一步:隨機產生數字或字母的方法

/// <summary>
  /// 生成验证码的随机数
  /// </summary>
  /// <returns>返回五位随机数</returns>
  private string GenerateCheckCode()
  {
    int number;
    char code;
    string checkCode = String.Empty;
 
    Random random = new Random();
 
    for (int i = 0; i < 5; i++)//可以任意设定生成验证码的位数
    {
      number = random.Next();
 
      if (number % 2 == 0)
        code = (char)(&#39;0&#39; + (char)(number % 10));
      else
        code = (char)(&#39;A&#39; + (char)(number % 26));
 
      checkCode += code.ToString();
    }
 
    Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));//写入COOKIS
    Session["CheckCode"] = checkCode; //写入Session,可以任意选一下
    return checkCode;
  }
登入後複製

第二步:產生圖片

/// <summary>
  /// 生成验证码图片
  /// </summary>
  /// <param name="checkCode"></param>
  private void CreateCheckCodeImage(string checkCode)
  {
    if (checkCode == null || checkCode.Trim() == String.Empty)
      return;
 
    Bitmap image = new 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.Silver), x1, y1, x2, y2);
      }
 
      Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
      LinearGradientBrush brush = new 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 < 100; 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.Silver), 0, 0, image.Width - 1, image.Height - 1);
 
      MemoryStream ms = new MemoryStream();
      image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
      Response.ClearContent();
      Response.ContentType = "image/Gif";
      Response.BinaryWrite(ms.ToArray());
    }
    finally
    {//释放对象资源
      g.Dispose();
      image.Dispose();
    }
登入後複製

*完整程式

先在裡面VS2005裡面的項目裡面加上一個加一個.aspx文件,在checkCode.aspx.cs 程式碼檔案中加入以下完整程式碼

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.IO;
using System.Drawing.Drawing2D;
 
public partial class checkCode : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    CreateCheckCodeImage(GenerateCheckCode());//调用下面两个方法;
  }
 
  /// <summary>
  /// 生成验证码的随机数
  /// </summary>
  /// <returns>返回五位随机数</returns>
  private string GenerateCheckCode()
  {
    int number;
    char code;
    string checkCode = String.Empty;
 
    Random random = new Random();
 
    for (int i = 0; i < 5; i++)//可以任意设定生成验证码的位数
    {
      number = random.Next();
 
      if (number % 2 == 0)
        code = (char)(&#39;0&#39; + (char)(number % 10));
      else
        code = (char)(&#39;A&#39; + (char)(number % 26));
 
      checkCode += code.ToString();
    }
 
    Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));//写入COOKIS
    Session["CheckCode"] = checkCode; //写入Session,可以任意选一下
    return checkCode;
  }
 
 
  /// <summary>
  /// 生成验证码图片
  /// </summary>
  /// <param name="checkCode"></param>
  private void CreateCheckCodeImage(string checkCode)
  {
    if (checkCode == null || checkCode.Trim() == String.Empty)
      return;
 
    Bitmap image = new 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.Silver), x1, y1, x2, y2);
      }
 
      Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
      LinearGradientBrush brush = new 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 < 100; 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.Silver), 0, 0, image.Width - 1, image.Height - 1);
 
      MemoryStream ms = new MemoryStream();
      image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
      Response.ClearContent();
      Response.ContentType = "image/Gif";
      Response.BinaryWrite(ms.ToArray());
    }
    finally
    {//释放对象资源
      g.Dispose();
      image.Dispose();
    }
  }
 
}
登入後複製

上面產生驗證碼的頁面都做好了,我們來呼叫看看:

在你需要用到驗證碼的地方加了Image控件


這樣驗證碼就會顯示到Image控制項上面了!

顯示弄好了,當然我們要判斷一下使用者的輸入是否正確!

只要我們取得使用者輸入的值跟Cookis或Session比較就OK了

取Cookies的值Request.Cookies["CheckCode"].Value

取Session的值Session["CheckCode"].Value

取Session的值Session["CheckCode"].Value

                 似乎)最好先判斷Session是否空)

如果不要區分大小寫的話,就把用戶輸入的值和Cookies或Session的值都轉成大寫或都小寫 

附用法 

protected void Button1_Click(object sender, EventArgs e)
  {
    if (Request.Cookies["CheckCode"].Value == TextBox1.Text.Trim().ToString())
    {
      Response.Write("Cookies is right");
    }
    else
    {
      Response.Write("Cookies is wrong");
    }
 
    if (Session["CheckCode"] != null)
    {
      if (Session["CheckCode"].ToString().ToUpper() == TextBox1.Text.Trim().ToString().ToUpper())
        //这样写可以不能区分大小写
      {
        Response.Write("Session is right");
 
      }
      else
      {
        Response.Write("Session is wrong");
      }
    }
  }
登入後複製
以上就是本文的全部內容,教大家如何製作ASP.NET驗證碼,希望大家會喜歡。 🎜🎜更多詳解ASP.NET驗證碼的生成方法相關文章請關注PHP中文網! 🎜
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1322
25
PHP教程
1270
29
C# 教程
1250
24
c#.net的持續相關性:查看當前用法 c#.net的持續相關性:查看當前用法 Apr 16, 2025 am 12:07 AM

C#.NET依然重要,因為它提供了強大的工具和庫,支持多種應用開發。 1)C#結合.NET框架,使開發高效便捷。 2)C#的類型安全和垃圾回收機制增強了其優勢。 3).NET提供跨平台運行環境和豐富的API,提升了開發靈活性。

從網絡到桌面:C#.NET的多功能性 從網絡到桌面:C#.NET的多功能性 Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#作為多功能.NET語言:應用程序和示例 C#作為多功能.NET語言:應用程序和示例 Apr 26, 2025 am 12:26 AM

C#在企業級應用、遊戲開發、移動應用和Web開發中均有廣泛應用。 1)在企業級應用中,C#常用於ASP.NETCore開發WebAPI。 2)在遊戲開發中,C#與Unity引擎結合,實現角色控制等功能。 3)C#支持多態性和異步編程,提高代碼靈活性和應用性能。

c#.net適合您嗎?評估其適用性 c#.net適合您嗎?評估其適用性 Apr 13, 2025 am 12:03 AM

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

C#.NET與未來:適應新技術 C#.NET與未來:適應新技術 Apr 14, 2025 am 12:06 AM

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。

.NET中的C#代碼:探索編程過程 .NET中的C#代碼:探索編程過程 Apr 12, 2025 am 12:02 AM

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

將C#.NET應用程序部署到Azure/AWS:逐步指南 將C#.NET應用程序部署到Azure/AWS:逐步指南 Apr 23, 2025 am 12:06 AM

如何將C#.NET應用部署到Azure或AWS?答案是使用AzureAppService和AWSElasticBeanstalk。 1.在Azure上,使用AzureAppService和AzurePipelines自動化部署。 2.在AWS上,使用AmazonElasticBeanstalk和AWSLambda實現部署和無服務器計算。

C#和.NET運行時:它們如何一起工作 C#和.NET運行時:它們如何一起工作 Apr 19, 2025 am 12:04 AM

C#和.NET運行時緊密合作,賦予開發者高效、強大且跨平台的開發能力。 1)C#是一種類型安全且面向對象的編程語言,旨在與.NET框架無縫集成。 2).NET運行時管理C#代碼的執行,提供垃圾回收、類型安全等服務,確保高效和跨平台運行。

See all articles