using System;
using System.Threading.Tasks;
using GxPress.Common.Tools;
using GxPress.Result.Captcha;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using GxPress.Common.Extensions;
namespace GxPress.Api.AdminControllers
{
///
/// 验证码
///
[Route("api/admin/captcha")]
[ApiController]
public class AdminCaptchaController : ControllerBase
{
//验证码过期时间
private readonly IDistributedCache _cache;
public AdminCaptchaController(IDistributedCache cache) {
_cache = cache;
}
///
/// 获取验证码图片和Guid
///
[HttpGet("image")]
public async Task GetCaptchaImage()
{
await using var ms = CaptchaHelper.Create(out var code);
var guid = Guid.NewGuid();
//将Guid和验证码值存入redis
await _cache.SetAsync($"captcha:{guid.ToString()}", code, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
});
var result = new CaptchaResult
{
CaptchaImg = Convert.ToBase64String(ms.ToArray()),
CaptchaGuid = guid
};
return result;
}
}
}