.Net Core 實現圖片驗證碼


記錄自己的學習,參考了網上各位大佬的技術,往往在登錄的時候需要使用到驗證碼來進行簡單的一個校驗,這邊使用在.net core上進行生成圖片4位數驗證碼

思路很簡單=》 生成一個隨機數-》保存到服務端Session-》生成隨機碼對應的圖片給前端-》登錄的時候進行校驗(也可以在后端進行隨機碼的token加密,存到Cooick里面在前端進行校驗)

備注:

using System.DrawingCore;
using System.DrawingCore.Imaging;

一定要引用DrawingCore不然在Linux上驗證碼圖片是出不來的,項目會默認給你推薦System.Drawing

第一步:生成隨機數

private static string RndNum(int VcodeNum)
        {
            //驗證碼可以顯示的字符集合  
            string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p" +
                ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q" +
                ",R,S,T,U,V,W,X,Y,Z";
            string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分成數組   
            string code = "";//產生的隨機數  
            int temp = -1;//記錄上次隨機數值,盡量避避免生產幾個一樣的隨機數  

            Random rand = new Random();
            //采用一個簡單的算法以保證生成隨機數的不同  
            for (int i = 1; i < VcodeNum + 1; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化隨機類  
                }
                int t = rand.Next(61);//獲取隨機數  
                if (temp != -1 && temp == t)
                {
                    return RndNum(VcodeNum);//如果獲取的隨機數重復,則遞歸調用  
                }
                temp = t;//把本次產生的隨機數記錄起來  
                code += VcArray[t];//隨機數的位數加一  
            }
            return code;
        }

第二步:生成驗證碼圖片

public static MemoryStream Create(out string code, int numbers = 4)
        {
            code = RndNum(numbers);
            //Bitmap img = null;
            //Graphics g = null;
            MemoryStream ms = null;
            Random random = new Random();
            //驗證碼顏色集合  
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //驗證碼字體集合
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋體" };


            using (var img = new Bitmap((int)code.Length * 18, 32))
            {
                using (var g = Graphics.FromImage(img))
                {
                    g.Clear(Color.White);//背景設為白色

                    //在隨機位置畫背景點  
                    for (int i = 0; i < 100; i++)
                    {
                        int x = random.Next(img.Width);
                        int y = random.Next(img.Height);
                        g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
                    }
                    //驗證碼繪制在g中  
                    for (int i = 0; i < code.Length; i++)
                    {
                        int cindex = random.Next(7);//隨機顏色索引值  
                        int findex = random.Next(5);//隨機字體索引值  
                        Font f = new Font(fonts[findex], 15, FontStyle.Bold);//字體  
                        Brush b = new SolidBrush(c[cindex]);//顏色  
                        int ii = 4;
                        if ((i + 1) % 2 == 0)//控制驗證碼不在同一高度  
                        {
                            ii = 2;
                        }
                        g.DrawString(code.Substring(i, 1), f, b, 3 + (i * 12), ii);//繪制一個驗證字符  
                    }
                    ms = new MemoryStream();//生成內存流對象  
                    img.Save(ms, ImageFormat.Jpeg);//將此圖像以Png圖像文件的格式保存到流中  
                }
            }

            return ms;
        }

第三步:控制器調用方法生成隨機數圖片之后,進行隨機數的保存

 HttpContext.Session.SetString("LoginValidateCode", code);

備注:在使用Session的時候要進行Session服務的注冊

在ConfigureServices中 services.AddSession();

在Configure中app.UseSession();

最后在前端進行驗證碼圖片的綁定

<img style="justify-content:center" id="code" src="/Users/Login/GetVerifyCode"  />

點擊圖片進行驗證碼刷新

 

 

 function GetCode() {
        $.ajax({
            type: "GET",
            url: "/Users/Login/GetVerifyCode",
            data: {},
            dataType: "json",
            success: function (data) {
            },
            complete: function () {
                $("#code").attr('src', '/Users/Login/GetVerifyCode')
            }
        });
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM