-
Install the required nuget package
Install-Package NCaptcha.AspNetCore.SessionSms Install-Package NCaptcha.Targets.Sms.Aliyun
-
Add Options in the
appsettings.json
file. It depends on which SMS service you choose."CaptchaAliyunSms": { "AccountKeyId": "", "AccessKeySecret": "", "SmsServiceSignName": "", "SmsServiceTemplateCode": "" }
-
Register in DI
public void ConfigureServices(IServiceCollection services) { services.AddSession(); services.AddSessionBasedSmsCaptcha(builder => builder.UseAliyunSmsCaptcha(Configuration.GetSection("CaptchaAliyunSms").Bind); ); }
-
Configure the session
public void Configure(IApplicationBuilder app) { app.UseSession(); }
-
Add a API for sending captcha code
public class LoginModel : PageModel { private readonly ICaptchaGenerator _captchaGenerator; public LoginModel(ICaptchaGenerator captchaGenerator) { _captchaGenerator = captchaGenerator; } public async Task OnPostSendCaptchaAsync() => await _captchaGenerator.GenerateCaptchaAsync(); }
-
Validate the captcha
public class LoginModel : PageModel { private readonly ICaptchaValidator _captchaValidator; public LoginModel(ICaptchaValidator captchaValidator) { _captchaValidator = captchaValidator; } public async Task<IActionResult> OnPostAsync() { if (!await _captchaValidator.ValidateAsync(Input.Captcha)) { ModelState.AddModelError(nameof(InputModel.Captcha), "Invalid captcha."); return Page(); } } }