基于配置值的.NET Core验证属性

mon*_*nty 0 c# asp.net-identity .net-core asp.net-core

我正在寻找一种将配置(选项)中的值注入到验证属性的参数中的方法。

让我印象深刻的场景是脚手架身份用户界面。

它提供了配置有关密码长度的选项的可能性。但生成的注册页面上不尊重更改。这是因为页面上验证属性的值是硬编码的。

有人知道这是否可能吗?

zek*_*iri 5

如果我没记错的话,你正在尝试做一些下面不可能的事情:

public int passLength = 3;
public class Person
{
  [MaxLength(passLength)]
  public DateTime? DateOfBirth { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,没有解决方法。您可以尝试自定义验证器并根据需要使用配置服务。你可以检查这个示例代码

public class CustomPasswordAttribute : ValidationAttribute
{
  protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  {
    var configuration = (IConfiguration)validationContext
            .GetService(typeof(IConfiguration));

    if (!(value is String)) 
    {
      return new ValidationResult("Should be string");
    }

    int.TryParse(configuration["Validation:PasswordLength"], out int passLength);

    if (value.ToString().Length != passLength)
    {
      return new ValidationResult("Wrong Length");
    }

    return ValidationResult.Success;
  }
}

public class UserModel
{
  [CustomPassword]
  public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)