。NET核心验证属性基于配置值

问题描述 投票:0回答:2

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

让我大吃一惊的场景是脚手架的身份UI。

它可以配置有关密码长度的选项。但是更改不会在生成的注册页面上进行。这是因为在页面上,验证属性的值是硬编码的。

任何人都知道这是否可能吗?

c# asp.net-core .net-core asp.net-identity
2个回答
0
投票

可以使用启动时设置的选项来验证密码。

[这是一个剃须刀页面的示例,其中用多个验证器检查密码,并将任何错误添加到ModelState中,这些错误将出现在ValidationSummary中。

foreach (var validator in _userManager.PasswordValidators)
{
    var passCheck = await validator.ValidateAsync(_userManager, null, Input.Password);
    if (!passCheck.Succeeded)
    {
        foreach (var error in passCheck.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }
        return Page();
    }
}

因此简单的验证将在客户端执行,然后此代码将在服务器端运行以实施密码选项。


0
投票

如果我没记错,您正在尝试做以下不可能的事情:

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

据我所知,尚无解决方法。您可以尝试自定义验证程序,并根据需要使用配置服务。您可以检查此示例代码

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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.