2021-10-24

本文介绍了如何在 ASP.NET Core 中使用 .NET Core 控制器和视图实现验证码功能,包括创建验证码服务、验证用户输入和使用Session存储。同时,展示了如何在前端页面中集成验证码并进行验证。
摘要由CSDN通过智能技术生成

.net core 验证码

  1. 创建控制器HomeController
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using UserText.Models;

namespace UserText.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        //验证方法
        public static string VerificationCodeCacheFormat = "vcode_cache_{0}";
        public IActionResult ValidateCode()
        {
            VerificationCodeServices _vierificationCodeServices = new VerificationCodeServices();
            string code = "";
            System.IO.MemoryStream ms = _vierificationCodeServices.Create(out code);
            code = code.ToLower();//验证码不分大小写
            HttpContext.Session.SetString("SupportValidateCode", code);
            Response.Body.Dispose();
            var token = Guid.NewGuid().ToString();
            Response.Cookies.Append("validatecode", token);
            return File(ms.ToArray(), @"image/png");
        }

        public IActionResult IzUserVoder(string userVerCode)
        {
            if (VerifyUserInputCode(userVerCode))
            {
                HttpContext.Session.SetString("SupportValidateCode", "");
                return Json(1);
            }
            return Json(0);    
        }

        /// <summary>
        /// 验证码判断
        /// </summary>
        /// <param name="userVerCode"></param>
        /// <returns></returns>
        public bool VerifyUserInputCode(string userVerCode)
        {
            string vCode = HttpContext.Session.GetString("SupportValidateCode");
            if (vCode != userVerCode) return false;
            return true;
        }

    }
}

2 在Model中创建VerificationCodeServices类

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

namespace UserText.Models
{
    /// <summary>
    /// 图片验证码
    /// </summary>
    public class VerificationCodeServices
    {
        /// <summary>  
        /// 生成指定长度的随机字符串 
        /// </summary>  
        /// <param name="codeLength">字符串的长度</param>  
        /// <returns>返回随机数字符串</returns>  
        private string RndomStr(int codeLength)
        {
            string chars = "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[] charArray = chars.Split(new Char[] { ',' });
            string code = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 1; i < codeLength + 1; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(61);
                if (temp == t)
                {
                    return RndomStr(codeLength);
                }
                temp = t;
                code += charArray[t];
            }
            return code;
        }

        /// <summary>  
        /// 将生成的字符串写入图像文件  
        /// </summary>  
        /// <param name="code">验证码字符串</param>
        /// <param name="length">生成位数(默认4位)</param>  
        public MemoryStream Create(out string code, int length = 4)
        {
            code = RndomStr(length);
            Bitmap Img = null;
            Graphics graphics = null;
            MemoryStream ms = null;
            Random random = new Random();
            Color[] color = { 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", "宋体" }; 
            Img = new Bitmap((int)code.Length * 18, 32);
            graphics = Graphics.FromImage(Img);
            graphics.Clear(Color.White);


            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(Img.Width);
                int y = random.Next(Img.Height);
                graphics.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }

            for (int i = 0; i < code.Length; i++)
            {
                int colorIndex = random.Next(7);
                int fontIndex = random.Next(4); 
                Font font = new Font(fonts[fontIndex], 15, FontStyle.Bold); 
                Brush brush = new SolidBrush(color[colorIndex]); 
                int y = 4;
                if ((i + 1) % 2 == 0)
                {
                    y = 2;
                }
                graphics.DrawString(code.Substring(i, 1), font, brush, 3 + (i * 12), y);
            }
            ms = new MemoryStream();
            Img.Save(ms, ImageFormat.Png);
            graphics.Dispose();
            Img.Dispose();
            return ms;
        }
    }
}

  1. 创建视图页index
@{
    ViewData["Title"] = "Home Page";
}

<p>
    请输入验证码:<br>
    <input type="text" id="validateCode" class="form-control" />
    <img id="imgVerify" src="~/Home/ValidateCode"  alt="看不清?点击更换" onclick="this.src = this.src + '?'" style="vertical-align:middle;" /><br />
    <span id="code" style="color:red"></span>

</p>
<button onclick="addPush()">提交</button>

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

@section Scripts{
    <script type="text/javascript">
        $(function () {

        });
        var str = "?";
        function addPush() {
            $.ajax({
                url: 'Home/IzUserVoder',
                dataType: 'JSON',
                type: 'POST',
                data: {
                    userVerCode: $("#validateCode").val()
                },
                success: function (date) {
                    if (date == "0") {
                        $("#imgVerify").attr("src", "Home/ValidateCode" + str)
                        $("#validateCode").val("");
                        $("#code").css("color", "red");
                        $("#code").html("验证码不正确");
                        str += str;
                        return;
                    }
                    $("#code").css("color", "black");
                    $("#code").html("验证码正确");
                }
            })
        }

    </script>

}

最后别忘了配置session,因为是用把验证码放到session中在js里面判断验证码是否正确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值