程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#驗證碼的創立與運用示例

C#驗證碼的創立與運用示例

編輯:C#入門知識

C#驗證碼的創立與運用示例。本站提示廣大學習愛好者:(C#驗證碼的創立與運用示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#驗證碼的創立與運用示例正文


本文實例講述了C#驗證碼的創立與運用辦法。分享給大家供大家參考,詳細如下:

1、C#創立驗證碼

① 創立獲取驗證碼頁面(ValidateCode.aspx)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>獲取驗證碼</title>
</head>
<body>
  <form id="form1" runat="server">
    <div>獲取驗證碼</div>
  </form>
</body>
</html>

② 編寫獲取驗證碼代碼(ValidateCode.aspx.cs)

/// <summary>
/// 驗證碼類型(0-字母數字混合,1-數字,2-字母)
/// </summary>
private string validateCodeType = "0";
/// <summary>
/// 驗證碼字符個數
/// </summary>
private int validateCodeCount = 4;
/// <summary>
/// 驗證碼的字符集,去掉了一些容易混雜的字符
/// </summary>
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
protected void Page_Load(object sender, EventArgs e)
{
  //取消緩存
  Response.BufferOutput = true;
  Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
  Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
  Response.AppendHeader("Pragma", "No-Cache");
  //獲取設置參數
  if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
  {
    validateCodeType = Request.QueryString["validateCodeType"];
  }
  if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
  {
    int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
  }
  //生成驗證碼
  this.CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
  char code ;
  string checkCode = String.Empty;
  System.Random random = new Random();
  for (int i = 0; i < validateCodeCount; i++)
  {
    code = character[random.Next(character.Length)];
    // 要求全為數字或字母
    if (validateCodeType == "1")
    {
      if ((int)code < 48 || (int)code > 57)
      {
        i--;
        continue;
      }
    }
    else if (validateCodeType == "2")
    {
      if ((int)code < 65 || (int)code > 90)
      {
        i--;
        continue;
      }
    }
    checkCode += code;
  }
  Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
  this.Session["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*15.0+40)), 23);
  System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  try
  {
    //生成隨機生成器
    Random random = new Random();
    //清空圖片背風光
    g.Clear(System.Drawing.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 System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
    }
    System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
    int cySpace = 16;
    for (int i = 0; i < validateCodeCount; i++)
    {
      g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
    }
    //畫圖片的前景樂音點
    for (int i = 0; i < 100; i++)
    {
      int x = random.Next(image.Width);
      int y = random.Next(image.Height);
      image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
    }
    //畫圖片的邊框線
    g.DrawRectangle(new System.Drawing.Pen(System.Drawing.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);
    Response.ClearContent();
    Response.ContentType = "image/Gif";
    Response.BinaryWrite(ms.ToArray());
  }
  finally
  {
    g.Dispose();
    image.Dispose();
  }
}

2、驗證碼的運用

① 驗證碼的前段顯示代碼
復制代碼 代碼如下:<img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="點擊刷新驗證碼" title="點擊刷新驗證碼" >

② 創立驗證碼測試頁面(ValidateTest.aspx)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>驗證碼測試</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input runat="server" id="txtValidate" />
    <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="點擊刷新驗證碼" title="點擊刷新驗證碼" >
    <asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click" />
  </div>
  </form>
</body>
</html>

③ 編寫驗證碼測試的提交代碼(ValidateTest.aspx.cs)

protected void btnVal_Click(object sender, EventArgs e)
{
  bool result = false;  //驗證後果
  string userCode = this.txtValidate.Value; //獲取用戶輸出的驗證碼
  if (String.IsNullOrEmpty(userCode))
  {
    //請輸出驗證碼
    return;
  }
  string validCode = this.Session["CheckCode"] as String; //獲取零碎生成的驗證碼
  if (!string.IsNullOrEmpty(validCode))
  {
    if (userCode.ToLower() == validCode.ToLower())
    {
      //驗證成功
      result = true;
    }
    else
    {
      //驗證失敗
      result = false;
    }
  }
}

更多關於C#相關內容感興味的讀者可檢查本站專題:《C#圖片操作技巧匯總》、《C#罕見控件用法教程》、《WinForm控件用法總結》、《C#數據構造與算法教程》、《C#面向對象順序設計入門教程》及《C#順序設計之線程運用技巧總結》

希望本文所述對大家C#順序設計有所協助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved