我正在对 ASP.NET Core MVC (2.1) 中的输入字段进行自定义验证。 我想添加一个简单的验证码字段,要求用户输入一些可以在 appsettings.json 文件中轻松重新配置的数字。我知道有很多图书馆在做验证码,但这不是我想要的这种特殊情况。
我无法从 appsettings.json 获取值。下面的代码可以完美编译,但我不知道如何从 CaptchaCustomAttribute 类的 appsettings.json 文件中获取值。
这是我的代码:
// appsettings.json
{
"GeneralConfiguration": {
"Captcha": "123456"
}
}
// GeneralConfiguration.cs
public class GeneralConfiguration
{
public string Captcha { get; set; }
}
// startup.cs / dependency injection
public void ConfigureServices(IServiceCollection services)
{
services.Configure<GeneralConfiguration>(Configuration.GetSection("GeneralConfiguration"));
}
// form model
public class ContactFormModel {
... simplified
[Display(Name = "Captcha")]
[Required(ErrorMessage = "Required")]
[CaptchaCustom]
public string Captcha { get; set; }
}
// CaptchaCustomAttribute.cs
public sealed class CaptchaCustomAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null) return new ValidationResult("value cannot be null");
if (value.GetType() != typeof(string)) throw new InvalidOperationException("can only be used on string properties.");
// get value of Captcha here. How?
// this will fail for obvious reasons
//var service = (GeneralConfiguration)validationContext
// .GetService(typeof(GeneralConfiguration));
//if ((string)value == service.Captcha)
//{
// return ValidationResult.Success;
//}
return new ValidationResult("unspecified error");
}
}
最佳答案
除了一个小细节外,您在问题中注释掉的代码非常接近可以正常工作。当您使用 IServiceCollection.Configure<T>
,您正在添加(除其他事项外)IOptions<T>
的注册到 DI 容器,而不是注册 T
本身。这意味着您需要申请 IOptions<GeneralConfiguration>
在你的ValidationAttribute
实现,像这样:
var serviceOptions = (IOptions<GeneralConfiguration>)
validationContext.GetService(typeof(IOptions<GeneralConfiguration>));
var service = serviceOptions.Value;
关于c# - 如何使用 DataAnnotation 进行自定义验证并从配置 appsettings.json 中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52817453/