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/CodeCaptchaAttribute.cs

61 lines
2.3 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 CodeCaptchaAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var httpContext = validationContext.GetService<IHttpContextAccessor>().HttpContext;
var key = CodeCaptchaModel.Key;
var captcha = value?.ToString();
if (!string.IsNullOrEmpty(captcha))
{
var model = httpContext.Session.Get<CodeCaptchaModel>(key);
if (model is null)
{
return new ValidationResult("尚未发送验证码");
}
else
{
if (DateTime.UtcNow > model.ExpireDateUtc)
{
httpContext.Session.Remove(key);
return new ValidationResult("验证码已过期");
}
else
{
if (captcha == model.Captcha)
{
httpContext.Session.Remove(key);
return null;
}
else
{
model.ErrorCount += 1;
if (model.ErrorCount < model.MaxErrorLimit)
{
httpContext.Session.Set(key, model);
return new ValidationResult("请输入正确的验证码");
}
else
{
httpContext.Session.Remove(key);
return new ValidationResult("试错超出限制,请重新发送验证码");
}
}
}
}
}
else
{
return new ValidationResult("请输入验证码");
}
}
}
}