ZhiYi/ZhiYi.Core.Application/Services/Implements/CaptchaAppService.cs

43 lines
1.7 KiB
C#

namespace ZhiYi.Core.Application.Services.Implements
{
public class CaptchaAppService : ICaptchaAppService
{
private readonly IServiceProvider _serviceProvider;
private readonly IDatabase _redis;
private readonly ILogger<CaptchaAppService> _logger;
public CaptchaAppService(IServiceProvider serviceProvider, IConnectionMultiplexer redis, ILogger<CaptchaAppService> logger)
{
_serviceProvider = serviceProvider;
_redis = redis.GetDatabase();
_logger = logger;
}
public async Task<CaptchaResponseDto> GetCaptchaAsync()
{
var scope = _serviceProvider.CreateScope();
var captchaService = scope.ServiceProvider.GetRequiredService<CaptchaService>();
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("获取验证码失败");
}
}
}
}