using System; using System.ComponentModel.DataAnnotations; using Infrastructure.Extensions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace Infrastructure.Web.DataAnnotations { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public class ImageCaptchaAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var httpContext = validationContext.GetService().HttpContext; var key = ImageCaptchaModel.Key; var captcha = value?.ToString(); if (!string.IsNullOrEmpty(captcha)) { var model = httpContext.Session.Get(key); if (model is null) { return new ValidationResult("尚未发送验证码"); } else { if (DateTime.UtcNow > model.ExpireDateUtc) { httpContext.Session.Remove(key); return new ValidationResult("验证码已过期"); } else { var code = model.Captcha; if (captcha == code) { httpContext.Session.Remove(key); return null; } else { return new ValidationResult("请输入正确的验证码"); } } } } else { return new ValidationResult("请输入验证码"); } } } }