zoukankan      html  css  js  c++  java
  • .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')
                }
            });
        }
    出处:https://www.cnblogs.com/net-open/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。(尊重别人就是尊重自己,尊重笔者的劳动哦,转载请说明出处哦,商用请征得作者本人同意,谢谢!!!)
  • 相关阅读:
    机器学习笔记
    python学习笔记-day8
    python学习笔记-day7
    python学习笔记-day6
    python学习笔记-day5
    python习题
    単語
    bat批处理----copy和xcopy区别
    C#
    VB
  • 原文地址:https://www.cnblogs.com/net-open/p/12543033.html
Copyright © 2011-2022 走看看