.net 登录页面添加验证码功能

前端代码

 <form class="login-form" id="LoginForm">
     <h3 class="form-title" style="color:#fff;">请登录</h3>
     <div class="control-group">
         <label class="control-label visible-ie8 visible-ie9">手机号</label>
         <div class="controls">
             <div class="input-icon left">
                 <i class="icon-user"></i>
                 <input class="m-wrap" type="text" placeholder="用户名/手机号" id="UserName" name="UserName" value="" autocomplete="on" />
             </div>
         </div>
     </div>
     <div class="control-group">
         <label class="control-label visible-ie8 visible-ie9">密码</label>
         <div class="controls">
             <div class="input-icon left">
                 <i class="icon-lock"></i>
                 <input class="m-wrap placeholder-no-fix Password" id="Password" type="password" name="Password" placeholder="密码" value="" />
             </div>
         </div>
     </div>
     <div id="codeDiv" class="control-group">
         <label for="Code" class="sr-only">验证码</label>
         <input type="text" id="Code" name="Code" class="form-control" placeholder="验证码" required>

         <div id="codeNumDiv">
             <img id="imgCode" src="/AccountApi/ShowCode?id=1" />
             <a href="javascript:void(0)" onclick="changeCheckCode(); return false;">看不清,换一张</a>
         </div>
     </div>
     <div style="margin: -12px 0px 0px 0px;">
         <label class="checkbox" style="float: right">
             <a href="@Url.Action("PasswordRetrieval", "Account")" class="pull-right" style="color: #fff">忘记密码</a>
         </label>
     </div>
     <div class="form-actions" style="margin-bottom:0px!important">
         <div>
             <button id="logging" class="m-wrap btn blue" style="background-color: #F5634A;width:100%; padding: 7px 20px;display:none;" disabled>正在登录...</button>
             <button id="login" class="m-wrap btn blue" style="background-color: #F5634A;width:100%; padding: 7px 20px;">登录 <i class="m-icon-swapright m-icon-white"></i></button>
         </div>
     </div>

<script>
	//与验证码相关方法
	
	
$(function () {
    //点击图片,改变验证码
    $("#imgCode").click(changeCheckCode);
});

//改变当前图片地址
function changeCheckCode() {
    var old = $("#imgCode").attr("src");
    var now = new Date();
    var str = old +
        now.getDay() +
        now.getMinutes() +
        now.getSeconds();
    $("#imgCode").attr("src", str);
}
</script>

首先添加类直接复制就可以用

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ITCGB.ITDRH.Bll
{
    public class ValidateCode
    {
        /// <summary>
        /// 验证码长度 
        /// </summary>
        public int CodeLen { get; set; }
        /// <summary>
        /// 验证码
        /// </summary>
        public string VCode { get; private set; }
        /// <summary>
        /// 验证码图像
        /// </summary>
        public Bitmap VCodeImg { get; private set; }

        private int fineness = 70;//图片清晰度  数值越大越清晰
        private int imgWidth = 48;//图片宽度
        private int imgHeight = 24;//图片高度 
        private int fontSize = 14;//字体大小
        private string fontFamily = "Microsoft YaHei";//字体名称

        /// <summary>
        /// 生成验证码 
        /// </summary>
        public string CreateVCode(int codeLen = 4)
        {
            CodeLen = codeLen;

            string vCode = "";
            Random random = new Random();
            for (int i = 0; i < CodeLen; i++)
            {
                int n = random.Next(10);
                vCode += n.ToString();
            }
            VCode = vCode;
            return vCode;
        }

        /// <summary>
        /// 验证码图像Byte
        /// </summary>
        /// <returns></returns>
        public byte[] GetCodeImgByte()
        {
            VCodeImg = new Bitmap(imgWidth, imgHeight);
            //生成像素点
            DrawPixel(VCodeImg);
            //绘制验证码图像
            DrewVCode(VCodeImg, VCode);
            //Bitmap转byte[]
            byte[] imgByte = BitmapToByte(VCodeImg);

            return imgByte;
        }

        /// <summary>
        /// 生成像素点
        /// </summary>
        private void DrawPixel(Bitmap bitmap)
        {
            Random random = new Random();
            for (int i = 0; i < bitmap.Width; i++)
            {
                for (int j = 0; j < bitmap.Height; j++)
                {
                    if (random.Next(90) <= fineness)
                        bitmap.SetPixel(i, j, Color.LightGray);
                }
            }
        }

        /// <summary>
        /// 绘制验证码图像 
        /// </summary>
        /// <param name="bitmap"></param>
        private void DrewVCode(Bitmap bitmap, string vCode)
        {
            Graphics g = Graphics.FromImage(bitmap);
            Font font = new Font(fontFamily, fontSize, FontStyle.Regular);
            g.DrawString(vCode, font, Brushes.Black, 0, 0);
        }

        /// <summary>
        /// Bitmap转byte[]
        /// </summary>
        private byte[] BitmapToByte(Bitmap bitmap)
        {
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Bmp);
            byte[] imgByte = ms.GetBuffer();
            return imgByte;
        }
    }
}

调用

public ActionResult ShowCode()
{
    ValidateCode validateCode = new ValidateCode();

    //生成验证码
    string vCode = validateCode.CreateVCode();

    // 清除旧的验证码,如果存在
    if (Session["vCode"] != null)
    {
        Session.Remove("vCode");
    }

    // 设置新的验证码,并设置过期时间为1分钟
    Session["vCode"] = vCode;
    Session.Add("vCodeTime", DateTime.Now);

    //生成验证码图像Byte
    byte[] imgByte = validateCode.GetCodeImgByte();

    return File(imgByte, @"Content/img/ValidateCodeImg");
}

登录时验证

 /// <summary>
 /// 登录
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 [LogInfo("登录提交", "登录提交")]
 public async System.Threading.Tasks.Task<ActionResult> Login(LoginViewModel model, string returnUrl)
 {
     /**
      * 1、使用UserName获取用户,如果获取到用户,则使用UserName登录
      * 2、检测是有为手机号,是的话查是否有使用该手机号的用户
      * 3、如果有该用户,获取到用户的UserName,转到1
      */
     //处理验证码
     string strCode = model.Code;

     string sessionCode = Session["vCode"] as string;
     if (sessionCode == null)
     {
         return Json(new { success = false, msg = "验证码已过期" }, JsonRequestBehavior.AllowGet);
     }

     string vCode = Session["vCode"].ToString();
     DateTime vCodeTime = (DateTime)Session["vCodeTime"];

     // 检查验证码是否在一分钟内
     if (DateTime.Now.Subtract(vCodeTime).TotalMinutes > 1)
     {
         // 清除过期的验证码
         Session.Remove("vCode");
         Session.Remove("vCodeTime");
         return Json(new { success = false, msg = "验证码已过期" }, JsonRequestBehavior.AllowGet);
     }

     if (strCode != sessionCode)
     {
         return Json(new { success = false, msg = "验证码错误" }, JsonRequestBehavior.AllowGet);
     }
     
 //正常登录逻辑省略
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值