使用.Net Core实现的一个图形验证码
SimpleCaptcha是一個使用簡單,基于.Net Standard 2.0的圖形驗證碼模塊。它的靈感來源于Edi.Wang的這篇文章https://edi.wang/post/2018/10/13/generate-captcha-code-aspnet-core,我將其中生成驗證碼的代碼抽取出來進行封裝得到了這個模塊。下面介紹一下使用方式。
基本使用方式
安裝SimpleCaptcha
在Nuget中搜索安裝SimpleCaptcha
安裝緩存模塊
SimpleCaptcha依賴Microsoft.Extensions.Caching.Abstractions模塊用來存儲驗證碼,所以你需要在項目中根據(jù)自己的需要安裝相應(yīng)的實現(xiàn)包,例如這里我使用Microsoft.Extensions.Caching.Memory
Startup
修改Startup.cs文件注入相應(yīng)的服務(wù):
services.AddMemoryCache().AddSimpleCaptcha(builder =>{builder.UseMemoryStore();});注入ICaptcha接口
在Controller中注入核心接口ICaptcha
private readonly ICaptcha _captcha;public HomeController(ICaptcha captcha) {_captcha = captcha; }生成驗證碼
使用ICaptcha接口的Generate方法生成驗證碼
public IActionResult Captcha(string id) {var info = _captcha.Generate(id);var stream = new MemoryStream(info.CaptchaByteData);return File(stream, "image/png"); }驗證
使用ICaptcha接口的Validate方法對用戶的提交進行驗證
public IActionResult Validate(string id, string code) {var result = _captcha.Validate(id, code);return Json(new { success = result }); }完整的例子可以在這里找到:https://github.com/1992w/SimpleCaptcha/tree/master/src/SimpleCaptcha.Demo
配置
SimpleCaptcha預(yù)留了一些默認的配置項,你可以根據(jù)需要自行修改。
設(shè)置驗證碼長度
services.AddSimpleCaptcha(builder => {builder.AddConfiguration(options =>{options.CodeLength = 6;}); });設(shè)置圖片大小
services.AddSimpleCaptcha(builder => {builder.AddConfiguration(options =>{options.ImageWidth = 100;options.ImageHeight = 36;}); });設(shè)置區(qū)分大小寫
默認情況下驗證不區(qū)分大小寫
services.AddSimpleCaptcha(builder => {builder.AddConfiguration(options =>{options.IgnoreCase = false;}); });設(shè)置驗證碼有效期
驗證碼默認的有效期為5分鐘
services.AddSimpleCaptcha(builder => {builder.AddConfiguration(options =>{options.ExpiryTime =TimeSpan.FromMinutes(10);}); });設(shè)置字符集
SimpleCaptcha提供了ICaptchaCodeGenerator接口用來生成字符,默認的實現(xiàn)是從字符集012346789ABCDEFGHIJKLMNOPQRSTUVWXYZ中隨機生成,你可以繼承ICaptchaCodeGenerator接口實現(xiàn)自己的需求。
public class MyCaptchaCodeGenerator : ICaptchaCodeGenerator {public string Generate(int length){throw new NotImplementedException();} }配置自己的生成器
services.AddSimpleCaptcha(builder => {builder.AddConfiguration(options =>{options.CodeGenerator = new MyCaptchaCodeGenerator();}); });設(shè)置個性化的圖片
如果默認生成的圖片你覺得不符合你的要求,你可以實現(xiàn)ICaptchaImageGenerator接口進行修改
public class CaptchaImageGenerator : ICaptchaImageGenerator {public byte[] Generate(int width, int height, string captchaCode){throw new NotImplementedException();} }services.AddSimpleCaptcha(builder => {builder.AddConfiguration(options =>{options.ImageGenerator = new CaptchaImageGenerator();}); });源代碼
所有源代碼可以在這里獲取:https://github.com/1992w/SimpleCaptcha
感謝
在這里感謝Edi.Wang分享。
最后
歡迎你對這個模塊提出任何的建議和想法。
總結(jié)
以上是生活随笔為你收集整理的使用.Net Core实现的一个图形验证码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 采用config方式灵活配置我们的Qua
- 下一篇: WPF 框架全构建环境虚拟机硬盘分享