MVC 生成验证码

时间:2024-07-11 06:57:41

在mvc 出现之前 生成验证码思路

在一个html页面上,生成一个验证码,在把这个页面嵌入到需要验证码的页面中。

JS生成验证码
<script type="text/javascript">
     jQuery(function ($) {

         /**生成一个随机数**/
         function randomNum(min, max) {
             return Math.floor(Math.random() * (max - min) + min);
         }
         /**生成一个随机色**/
         function randomColor(min, max) {
             var r = randomNum(min, max);
             var g = randomNum(min, max);
             var b = randomNum(min, max);
             return "rgb(" + r + "," + g + "," + b + ")";
         }
         var code = drawPic();
         document.getElementById("changeImg").onclick = function (e) {
             e.preventDefault();
             code = drawPic();
         }
         /**绘制验证码图片**/
         function drawPic() {
             var canvas = document.getElementById("canvas");
             var width = canvas.width;
             var height = canvas.height;
             //获取该canvas的2D绘图环境 
             var ctx = canvas.getContext('2d');
             ctx.textBaseline = 'bottom';
             /**绘制背景色**/
             ctx.fillStyle = randomColor(180, 240);
             //颜色若太深可能导致看不清
             ctx.fillRect(0, 0, width, height);
             /**绘制文字**/
             var str = 'ABCEFGHJKLMNPQRSTWXY123456789';

             var code = "";
             //生成四个验证码
             for (var i = 1; i <= 4; i++) {
                 var txt = str[randomNum(0, str.length)];
                 code = code + txt;
                 ctx.fillStyle = randomColor(50, 160);
                 //随机生成字体颜色
                 ctx.font = randomNum(15, 40) + 'px SimHei';
                 //随机生成字体大小
                 var x = 10 + i * 25;
                 var y = randomNum(25, 35);
                 var deg = randomNum(-45, 45);
                 //修改坐标原点和旋转角度
                 ctx.translate(x, y);
                 ctx.rotate(deg * Math.PI / 180);
                 ctx.fillText(txt, 0, 0);
                 //恢复坐标原点和旋转角度
                 ctx.rotate(-deg * Math.PI / 180);
                 ctx.translate(-x, -y);
             }

             /**绘制干扰线**/
             for (var i = 0; i < 3; i++) {
                 ctx.strokeStyle = randomColor(40, 180);
                 ctx.beginPath();
                 ctx.moveTo(randomNum(0, width / 2), randomNum(0, height / 2));
                 ctx.lineTo(randomNum(0, width / 2), randomNum(0, height));
                 ctx.stroke();
             }
             /**绘制干扰点**/
             for (var i = 0; i < 50; i++) {
                 ctx.fillStyle = randomColor(255);
                 ctx.beginPath();
                 ctx.arc(randomNum(0, width), randomNum(0, height), 1, 0, 2 * Math.PI);
                 ctx.fill();
             }
             $("#code").val(code);
             return code;
         }
     });
    
 </script>

在这里插入图片描述
在这里插入图片描述

MVC中验证码

》》》定义一个生成验证码的类

public class VerifyCodeHelper
    {
        public static Bitmap CreateVerifyCode(out string code)
        {
            //建立Bitmap对象,绘图
            Bitmap bitmap = new Bitmap(200, 60);
            Graphics graph = Graphics.FromImage(bitmap);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
            Random r = new Random();
            string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";

            StringBuilder sb = new StringBuilder();

            //添加随机的五个字母
            for (int x = 0; x < 5; x++)
            {
                string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
                sb.Append(letter);
                graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
            }
            code = sb.ToString();

            //混淆背景
            Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
            for (int x = 0; x < 6; x++)
                graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
            return bitmap;
        }
    }

》》》》Action

        /// <summary>
        /// 验证码 FileContentResult
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult VerifyCode()
        {
            string code = "";
            Bitmap bitmap = VerifyCodeHelper.CreateVerifyCode(out code);   
            //声明一个内存流      
            MemoryStream stream = new MemoryStream();
            //把bitmap存入这个  流中
            bitmap.Save(stream, ImageFormat.Gif);
            // Controller中File方法  返回  FileContentResult, 
            // FileContentResult继承FileResult,FileResult又继承    ActionResult
            return File(stream.ToArray(), "image/gif");//返回FileContentResult图片
        }
        /// <summary>
        /// 验证码  直接写入Response
        /// </summary>
        [AllowAnonymous]
        public void Verify()
        {
            string code = "";
            Bitmap bitmap = VerifyCodeHelper.CreateVerifyCode(out code);
         
            bitmap.Save(base.Response.OutputStream, ImageFormat.Gif);
            base.Response.ContentType = "image/gif";
        }

在html页面中

验证码图片