asp.net core 图片验证码,后台验证

时间:2024-01-05 12:31:08
验证方法:

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>