c# - 如何使用 DataAnnotation 进行自定义验证并从配置 appsettings.json 中获取值?

标签 c# asp.net-core asp.net-core-mvc

我正在对 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/

相关文章:

c# - 在 .NET 4.5 TypeInfo.DeclaredMembers 上过滤掉私有(private)成员

c# - 百万交易 - 提高网站性能

c# - <> 是什么意思?

c# - 无法将 System.Configuration.ConfigurationManager 添加到 .NET 核心应用程序

c# - 模块化单体中的跨模块通信

c# - MVC 6 中的自定义 Razor View 引擎

ASP.NET 5 MVC6 自定义 CSS 和 Javascript 放置约定

c# - 非常大的整数的快速乘法

css - ASP Net Core TagHelper 添加 CSS 类

razor - asp.net 有条件地禁用标签助手 (textarea)