39 lines
1.3 KiB
C#
Raw Normal View History

2026-03-30 20:47:40 +08:00
using Microsoft.Extensions.Caching.Memory;
using YD_Event.Application.Common.Dtos;
using YD_Event.Application.Sms;
namespace YD_Event.Application.Common;
[ApiDescriptionSettings("通用服务")]
public class SmsService : IDynamicApiController, ITransient
{
private readonly AliyunSmsService _smsService;
private readonly IMemoryCache _memoryCache;
public SmsService(AliyunSmsService smsService, IMemoryCache memoryCache)
{
_smsService = smsService;
_memoryCache = memoryCache;
}
[HttpPost("sms/sendVerificationCode")]
[DisplayName("发送短信验证码")]
[AllowAnonymous]
public async Task SendVerificationCode([FromBody] SendVerificationCodeInput input)
{
var limitCacheKey = $"sms:code:limit:{input.Phone}";
if (_memoryCache.TryGetValue(limitCacheKey, out _))
{
throw Oops.Bah("发送太频繁,请稍后再试");
}
string code = input.Code ?? new Random().Next(100000, 999999).ToString();
await _smsService.SendVerificationCode(input.Phone, code);
var codeCacheKey = $"sms:code:{input.Phone}";
_memoryCache.Set(codeCacheKey, code, TimeSpan.FromMinutes(5));
_memoryCache.Set(limitCacheKey, "1", TimeSpan.FromMinutes(1));
}
}