You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/Infrastructure/Web/DataAnnotations/ImageCaptchaAttribute.cs

52 lines
1.9 KiB

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<IHttpContextAccessor>().HttpContext;
var key = ImageCaptchaModel.Key;
var captcha = value?.ToString();
if (!string.IsNullOrEmpty(captcha))
{
var model = httpContext.Session.Get<ImageCaptchaModel>(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("请输入验证码");
}
}
}
}