验证方法:

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();
//ViewBag.code = code;
var token = Guid.NewGuid().ToString();
ViewBag.token = token;
var cacheKey = string.Format(VerificationCodeCacheFormat, token);
_memoryCache.Set(cacheKey, code, new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes()));
CookieOptions options = new CookieOptions();
Response.Cookies.Append("validatecode", token);
return File(ms.ToArray(), @"image/png");
}
/// <summary>
/// 验证码改为后台验证
/// </summary>
/// <param name="userToken"></param>
/// <param name="userVerCode"></param>
/// <returns></returns>
public bool VerifyUserInputCode(string userToken, string userVerCode)
{
var cacheKey = string.Format(VerificationCodeCacheFormat, userToken.ToString());
var vCode = "";
if (!_memoryCache.TryGetValue(cacheKey, out vCode)) return false;
if (vCode.ToLower() != userVerCode.ToLower()) return false;
_memoryCache.Remove(cacheKey);
return true;
}

生成验证码及其图片

using System;
using System.Collections.Generic;
using System.DrawingCore;
using System.DrawingCore.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace homepage.Classes
{
///NuGet中引入第三方 ZKWeb.System.Drawing 3.0版本 /// <summary>
/// 图片验证码
/// </summary>
public class VerificationCodeServices
{
/// <summary>
/// 生成指定长度的随机字符串
/// </summary>
/// <param name="codeLength">字符串的长度</param>
/// <returns>返回随机数字符串</returns>
private string RndomStr(int codeLength)
{
//组成字符串的字符集合 0-9数字、大小写字母
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 = -;//记录上次随机数值,尽量避避免生产几个一样的随机数
Random rand = new Random();
//采用一个简单的算法以保证生成随机数的不同
for (int i = ; i < codeLength + ; i++)
{
if (temp != -)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化随机类
}
int t = rand.Next();
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 = )
{
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 * , );
graphics = Graphics.FromImage(Img);//从Img对象生成新的Graphics对象
graphics.Clear(Color.White);//背景设为白色 //在随机位置画背景点 for (int i = ; i < ; i++)
{
int x = random.Next(Img.Width);
int y = random.Next(Img.Height);
graphics.DrawRectangle(new Pen(Color.LightGray, ), x, y, , );
} //验证码绘制在graphics中 for (int i = ; i < code.Length; i++)
{
int colorIndex = random.Next();//随机颜色索引值
int fontIndex = random.Next();//随机字体索引值
Font font = new Font(fonts[fontIndex], , FontStyle.Bold);//字体
Brush brush = new SolidBrush(color[colorIndex]);//颜色
int y = ;
if ((i + ) % == )//控制验证码不在同一高度
{
y = ;
}
graphics.DrawString(code.Substring(i, ), font, brush, + (i * ), y);//绘制一个验证字符
}
ms = new MemoryStream();//生成内存流对象
Img.Save(ms, ImageFormat.Png);//将此图像以Png图像文件的格式保存到流中
graphics.Dispose();
Img.Dispose();
return ms;
}
}
}

以上只适用于一个页面只有一个的验证码的情况,下面改进为可以一个页面多个验证码:

ValidateCode方法改为:

   public IActionResult ValidateCode(string identify = "")
{
VerificationCodeServices _vierificationCodeServices = new VerificationCodeServices();
string code = "";
System.IO.MemoryStream ms = _vierificationCodeServices.Create(out code);
code = code.ToLower();//验证码不分大小写
Response.Body.Dispose();
var token = Guid.NewGuid().ToString();
ViewBag.token = token;
var cacheKey = string.Format(VerificationCodeCacheFormat, token);
_memoryCache.Set(cacheKey, code, new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes()));
CookieOptions options = new CookieOptions();
Response.Cookies.Append("validatecode"+ identify, token);
return File(ms.ToArray(), @"image/png");
}

当页面只有一个验证码的时候,页面写法:

                                                      <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;" />
</p>

当页面多个验证码:

                                    <p>
<input name="verification_code" type="text" maxlength="5" id="code_other" class="form-control tbText">
<img id="imgVerifyOther" src="~/Home/ValidateCode?identify=other" alt="看不清?点击更换" onclick="this.src = 'ValidateCode?identify=other&' + Math.random()" style="vertical-align:middle;" />
</p>

asp.net core 图片验证码,后台验证的更多相关文章

  1. asp.net core 3.x 身份验证-3cookie身份验证原理

    概述 上两篇(asp.net core 3.x 身份验证-1涉及到的概念.asp.net core 3.x 身份验证-2启动阶段的配置)介绍了身份验证相关概念以及启动阶段的配置,本篇以cookie身份 ...

  2. 从零搭建一个IdentityServer——聊聊Asp.net core中的身份验证与授权

    OpenIDConnect是一个身份验证服务,而Oauth2.0是一个授权框架,在前面几篇文章里通过IdentityServer4实现了基于Oauth2.0的客户端证书(Client_Credenti ...

  3. ASP.NET Core CMS管理后台

    ASP.NET Core+LayUI+MySql CMS管理后台,主要功能包括 登录.修改密码,账号管理,菜单管理,角色权限管理等 由于工作之外,抽时间写的,用于学习交流,请慎重用于生产环境 项目概要 ...

  4. ASP.NET中图片验证码与js获取验证码的值

    现在的程序中,为了防止用户恶意点击,我们一般都会加上验证,现在比较普遍的是加上图片验证码或者手机短信验证.验证码一般都是防机器不防人,有效的防止了恶意点击. 那么在webform中如何生成动态的图片验 ...

  5. asp.net mvc中的后台验证

    asp.net mvc的验证包含后台验证和前端验证.后台验证主要通过数据注解的形式实现对model中属性的验证,其验证过程发生在model绑定的过程中.前端验证是通过结合jquery.validate ...

  6. 在ASP.NET Core中实现自定义验证特性(Custom Validation Attribute)

    这是我们在实际ASP.NET Core项目中用到的,验证用户名中是否包含空格. 开始是这么实现的(继承ValidationAttribute,重写IsValid方法): public class No ...

  7. 基于ASP.NET Core Data Protection生成验证token

    ASP.NET Core Data Protection 不仅提供了非对称加密能力,而且提供了灵活的秘钥存储方式以及一致的加解密接口(Protect与Unprotect).Session中用到了它,C ...

  8. dotnet Core 图片验证码

    9102年了,.NET Core 2.x已经稳定,但是还是有很多人搞不定.NET Core的图片验证码. 下面说重点 1.引用Nuget包:System.Drawing.Common 2.像NET F ...

  9. asp.net core 3.x 身份验证-1涉及到的概念

    前言 从本篇开始将围绕asp.net core身份验证写个小系列,希望你看完本系列后,脑子里对asp.net core的身份验证原理有个大致印象.至于身份验证是啥?与授权有啥联系?就不介绍了,太啰嗦. ...

随机推荐

  1. LaTeX IEEE模板

    因为课程作业的要求需要完成一篇IEEE格式的论文,所以选择入门LaTeX.但是期间遇到了各种各样莫名其妙的坑.前前后后挣扎了两个多星期终于完成了IEEE模板的设置.下面详细记录一下让我深恶痛绝的心路历 ...

  2. RabbitMQ简单应用の公平分发(fair dipatch)

    公平分发(fair dipatch)和轮询分发其实基本一致,只是每次分发的机制变了,由原来的平均分配到现在每次只处理一条消息 1.MQ连接工厂类Connection package com.mmr.r ...

  3. mysql定时任务用到存储过程和定时任务

    需求: 需要将t_app_message中的消息(将要被发送的消息)给每一个学生发送一遍,并且在发送完成后,将消息置为已发送状态已发送状态. 一言不合上代码 /*删除存储过程*/ drop proce ...

  4. 数字图像处理的Matlab实现(4)—灰度变换与空间滤波

    第3章 灰度变换与空间滤波(2) 3.3 直方图处理与函数绘图 基于从图像亮度直方图中提取的信息的亮度变换函数,在诸如增强.压缩.分割.描述等方面的图像处理中扮演着基础性的角色.本节的重点在于获取.绘 ...

  5. dubbo源码分析8——服务暴露概述

    从上文中可知,com.alibaba.dubbo.config.spring.ServiceBean类是负责解析<dubbo:service/>的配置的,下面是它的类图 从类图上可知它继承 ...

  6. 使用cstdiofile在vs2010中无法写入中文的问题

    在VC2010环境下, 以下代码无法实现使用CStdioFile向文本文件中写入中文(用notepad.exe查看不到写入的中文) CStdioFile file; file.Open(…); fil ...

  7. 题解-ZeroJudge-c686 高斯符號

    Problem ZeroJudge Solution 考慮到\(\lfloor \frac {km}n\rfloor\)等同於\(km\)整除\(n\),換種表示方法就是\(km\)減去\(km\)模 ...

  8. NO-CARRIER

    自己动手写了创建虚拟接口,删除虚拟接口程序,频繁调用创建删除时,有时将接口up起来时会报错: Name not unique on network 利用ip link命令来查看接口(及其对应的索引) ...

  9. Android来电拦截及来电转移

    1. 电话拦截这个功能大家可能都知道了,就是利用反射原理调用ITelephony的隐藏方法来实现.这个就不说了,在附件的代码里有.2.拦截后提示忙音/空号/已关机/已停机这个功能其实是要用到MMI指令 ...

  10. 让NotePad++添加到右键快捷方式

    添加后的效果图: 操作方式: 第一步:在桌面上新建一个txt文本文档,然后将写入如下内容 Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT ...