namespace ZhiYi.Core.Application.Services.Implements { public class CaptchaAppService : ICaptchaAppService { private readonly IServiceProvider _serviceProvider; private readonly IDatabase _redis; private readonly ILogger _logger; public CaptchaAppService(IServiceProvider serviceProvider, IConnectionMultiplexer redis, ILogger logger) { _serviceProvider = serviceProvider; _redis = redis.GetDatabase(); _logger = logger; } public async Task GetCaptchaAsync() { var scope = _serviceProvider.CreateScope(); var captchaService = scope.ServiceProvider.GetRequiredService(); try { //生成验证码 var captchaText = captchaService.GenerateCaptchaText(); //生成验证码图片 var captcha = captchaService.GenerateCaptchaImageByImageSharp(captchaText); var captchaId = Guid.NewGuid().ToString(); if (!captchaText.IsNullOrEmpty() && captcha.Length > 0) { _redis.StringSet($"captcha:{captchaId}", captchaText, TimeSpan.FromMinutes(2)); //_redis.StringSet($"captcha:{captchaId}", captchaText); } return await Task.FromResult(new CaptchaResponseDto { File = captcha, CaptchaId = captchaId, Captcha = captchaText }); } catch(Exception ex) { _logger.LogError("获取验证码失败:{message}", ex.Message); throw new Exception("获取验证码失败"); } } } }