使用.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模塊用來存儲驗證碼,所以你需要在項目中根據自己的需要安裝相應的實現包,例如這裏我使用 Microsoft.Extensions.Caching.Memory
Startup
修改Startup.cs文件注入相應的服務:
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預留了一些默認的配置項,你可以根據需要自行修改。
設置驗證碼長度
services.AddSimpleCaptcha(builder => { builder.AddConfiguration(options => { options.CodeLength = 6; }); });
設置圖片大小
services.AddSimpleCaptcha(builder => { builder.AddConfiguration(options => { options.ImageWidth = 100; options.ImageHeight = 36; }); });
設置區分大小寫
默認情況下驗證不區分大小寫
services.AddSimpleCaptcha(builder => { builder.AddConfiguration(options => { options.IgnoreCase = false; }); });
設置驗證碼有效期
驗證碼默認的有效期爲5分鐘
services.AddSimpleCaptcha(builder => { builder.AddConfiguration(options => { options.ExpiryTime =TimeSpan.FromMinutes(10); }); });
設置字符集
SimpleCaptcha提供了 ICaptchaCodeGenerator
接口用來生成字符,默認的實現是從字符集 012346789ABCDEFGHIJKLMNOPQRSTUVWXYZ
中隨機生成,你可以繼承ICaptchaCodeGenerator接口實現自己的需求。
public class MyCaptchaCodeGenerator : ICaptchaCodeGenerator { public string Generate(int length) { throw new NotImplementedException(); } }
配置自己的生成器
services.AddSimpleCaptcha(builder => { builder.AddConfiguration(options => { options.CodeGenerator = new MyCaptchaCodeGenerator(); }); });
設置個性化的圖片
如果默認生成的圖片你覺得不符合你的要求,你可以實現 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 分享。
最後
歡迎你對這個模塊提出任何的建議和想法。