MVC项目验证码的生成


生成过程

前端调用

html代码

                <div>
                    <img id="imgcode" class="col-md-2 control-label" src="~/Login/GetValidateCode" alt="验证码" />
                    <a id="switchCode">换一张</a>
                </div>
 

js代码

<script type="text/javascript">
    $("#switchCode").click(function () {
        $("#imgcode").attr("src", "/Login/GetValidateCode?" + Math.random())
    })
    $("#imgcode").click(function () {
        $("#imgcode").attr("src", "/Login/GetValidateCode?" + Math.random())
    })
</script>

控制器


    public ActionResult Index()
        {

            return View();
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetValidateCode()
        {
            VerifyCode vc = new VerifyCode();
            //byte[] bytes = vc.GetVerifyCode();
            return File(vc.GetVerifyCode(), @"image/jpeg");
        }

验证码图片生成类

    /// <summary>
    /// 验证码生成
    /// </summary>
    public class VerifyCode
    {
        public byte[] GetVerifyCode()
        {
            int codeW = 80;//宽
            int codeH = 20;//高
            int fontSize = 16;//大小
            string chkCode = string.Empty;
            //颜色列表,用于验证码的噪线、噪点
            Color[] color = { Color.Black, Color.Red, Color.Green, Color.Blue, Color.Brown, Color.DarkBlue };
            //生成验证码字符数组
            char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'e', 'f', 'g', 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
            //验证码字体设定
            string[] font = { "Times New Roman" };
            //随机
            Random rnd = new Random();
            //生成验证码
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            //加密验证码写入
            WebHelper.WriteSession("nfine_session_verifycode", Md5.Equals(chkCode.ToLower(), 16));
            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH);//设置宽高
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);//背景白
            //画噪点噪线
            for (int i = 0; i < 3; i++)
            {
                //噪线范围
                int x1 = rnd.Next(codeW);
                int y1 = rnd.Next(codeH);
                int x2 = rnd.Next(codeW);
                int y2 = rnd.Next(codeH);
                Color clr = color[rnd.Next(color.Length)];
                //写到画布
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);

            }
            //将验证码写入内存流
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }
        }

    }

WebHelper

        /// <summary>
        /// T:Session键值类型
        /// key:Session键名
        /// value:Session键值
        /// </summary>
        /// <typeparam name="T">键值类型</typeparam>
        /// <param name="key">键名</param>
        /// <param name="value">键值</param>
        public static void WriteSession<T>(string key, T value)
        {
            if(key.IsEmpty())
            {
                return;
            }
            HttpContext.Current.Session[key] = value;
        }

Md5加密

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MusicStore.Models
{
    public class Md5
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密字符串</param>
        /// <param name="code">加密位数</param>
        /// <returns></returns>
        public static string md5(string str,int code)
        {
            string strEncrypt = string.Empty;
            if(code==16)
            {

                strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").Substring(8, 16);

            }
            if (code == 12)
            {

                strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");

            }
            return strEncrypt;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_17060989/article/details/85604710