在Custom Validator中获取授权信息

时间:2016-11-03 20:56:56

标签: c# validation reflection asp.net-core

我正在写asp.net核心,形式我有字符串字段PESEL(它是波兰的一些ID号)和布尔字段NoPeselPesel仅在未选中字段NoPesel时进行验证。

现在我要添加新功能:如果用户是登录/授权,则即使取消选中NoPesel也会关闭验证。

我不知道该怎么做。我应该尝试通过反思或某些背景来做到这一点吗?有人知道怎么做吗?

 public sealed class PeselValidator : ValidationAttribute
 {
    // private const string DefaultErrorMessage = "Nie poprawny numer pesel";

    public string NoPesel { get; set; }


    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (PeselRequired(validationContext.ObjectInstance, NoPesel))
        {
            return ValidationResult.Success;

        }


        if ((value == null) || (!ValidatePesel(value.ToString())) )
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));

        return ValidationResult.Success;
    }

    public override string FormatErrorMessage(string name)
    {
        return base.FormatErrorMessage(ErrorMessageResourceName);
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
        ErrorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());


    }

    private bool PeselRequired(object objectInstance, string NoPesel)
    {
        var propertyInfo = objectInstance.GetType().GetProperty(NoPesel);
        var x = propertyInfo.GetValue(objectInstance, null);
        return (bool)x;
    }

    public static bool ValidatePesel(string szPesel)
    {
        //some logic checking PESEL SUM
        return true;
    }

}

0 个答案:

没有答案