C# Web 端添加登入驗證碼

來源:互聯網
上載者:User

        寫在前面:最近做的學校項目需要添加登入驗證碼,而我又是一個剛轉專業到電腦的學渣,所以對添加 Web 端驗證碼一竅不通。不過在請教了同學,以及在網上找各種資料,經過自己的測試,算是加了一個簡單的登入驗證碼。下面把添加驗證碼的過程記錄一下,以便以後自己學習改進,也可以讓跟我一樣的小白同學省點找資料的功夫。


1) 首先,我們需要從網上找一個生產驗證碼圖片的類(主要是我不會自己寫)。看本篇文章的同學就不用找了,我直接把代碼貼在下面,具體的注釋,源碼的作者已經都寫了,大家都能看明白怎麼用,有機會再仔細研究下吧。


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace TestSecurityCode01.App_Start
{
    public class SecurityCode
    {
        /// <summary>
        /// 產生隨機的字串
        /// </summary>
        /// <param name="codeCount">驗證碼長度</param>
        /// <returns></returns>
        public string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,a,b,c,d,e,f,g,h,i,   g,k,l,m,n,o,p,q,r,F,G,H,I,G,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,s,t,u,v,w,x,y,z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }

        /// <summary>
        /// 建立驗證碼圖片
        /// </summary>
        /// <param name="validateCode">驗證碼無幹擾字串</param>
        /// <returns></returns>
        public byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 22.0), 40);
            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, x2, y1, y2);
                }
                Font font = new Font("Arial", 20, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue,Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 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 stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);

                //輸出圖片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}


然後,我們需要建一個類,名字就叫 SecurityCode ,把這個類放在一個你能找到的檔案夾下,我放到了這裡(別問為什麼放這裡,我只是為了好找)


2)我們需要在 控制器裡添加一個生產驗證碼圖片的方法,我這裡是添加到了HomeController。首先來張圖:


下面貼上代碼(不貼代碼,文章還有什麼意義。)


           static string  securityCode_input = "";
        public ActionResult GetSecurityCode()
        {
            SecurityCode code = new SecurityCode();
            securityCode_input = code.CreateRandomCode(4);
            byte[] buf = code.CreateValidateGraphic(securityCode_input);
            //securityCode_input = buf.ToString();
            return File(buf, "image/Jpeg");
        }


注意 securityCode_input這個變數應該是靜態,否則每次進入控制器,該變數都會重設。這個變數就是隨機產生的字串驗證碼。  大家可以調試一遍走一走。(這段代碼就是HomeController 裡面的代碼,而 HomeController  的視圖就是我們需要添加驗證碼的頁面,在本文裡是 Index.cshtml )


3)下面就是在前台頁面調用該驗證碼了,這裡有兩種方法,個人比較推薦第二種,雖然第二種有時候會出異常。。。照例先來截圖:

方法一:



下面貼上代碼:

<script type="text/javascript">
    window.onload = function () {
        $("#secImg").click(function () {
            ///注意後面的flag是必須的,如果不添加會導致部分瀏覽器不能重新整理驗證碼
            $("#secImg").attr("src", "GetSecurityCode?flag=" + Math.random());
        });
    }
</script>


<form action="CheckSecurityCode" method="post">
<div style="width:100px;height:80px;margin:50px auto">
    <input type="text" id="securityCode" name="securityCode" required>
    <p><img src="~/Home/GetSecurityCode" id="secImg" title="換一張" /></p>
    @*如果不添加 ~/Home/ 則有時會出現404錯誤,Home 代表控制器的名稱,也就是HomeController*@
</div>
    <p><input type="submit"> </p>
</form>



方法二:


下面貼上代碼:

<script type="text/javascript">
    window.onload = function () {    
        $("#secImg").click();      
    }
</script>


<form action="~/Home/CheckSecurityCode" method="post">
<div style="width:100px;height:80px;margin:50px auto">
    <input type="text" id="securityCode" name="securityCode" required>
    <p><img onclick="this.src= document.location.protocol + '/Home/GetSecurityCode?flag=' + Math.random(); " id="secImg" title="換一張" /></p>
     @* 注意後面的flag是必須的,如果不添加會導致部分瀏覽器不能重新整理驗證碼 *@
</div>

<p><input type="submit"> </p>
</form>


結束。。。。。。。。。。。。。。。。。。。


下面來張運行成功截圖:






寫在後面:大家發現錯誤一定幫我指出,謝謝。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.