【问题标题】:Variables in model validation on MVCMVC 模型验证中的变量
【发布时间】:2012-06-25 17:04:26
【问题描述】:

所以在 MVC 中使用 .NET Membership 系统时,密码策略是在 web.config 文件中定义的。例如 minPasswordLength 在membership->profiles 中定义。

当使用视图时,可以使用@Membership 组件访问它

Passwords must be at least @Membership.MinRequiredPasswordLength characters long.

但是,如果您查看示例 MVC 应用程序中的默认模型,它会说

 [Required]
 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
 [DataType(DataType.Password)]
 [Display(Name = "New Password")]
 public string NewPassword { get; set; }

我很好奇的部分是MinimumLength = 6,因为这是硬编码的,这意味着如果我想更新密码长度,我不仅需要编辑 web.config(就像微软建议的那样)但也要在源代码中搜索对它的任何引用并在整个地方进行更改(可能不是最好的编程实践)。

有什么方法可以在属性中使用变量。我怀疑不会,因为这可能发生在编译时而不是运行时。如果没有人知道更好的模式来阻止我将来必须找到替换所有引用?

【问题讨论】:

    标签: c# asp.net-mvc validation membership-provider


    【解决方案1】:

    Here is an article 可以帮你解答问题。基本上,创建您自己的 DataAnnotation,从 web.config 中提取最小长度。

    为了后代,这里是引用站点中使用的代码:

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter , AllowMultiple = false, Inherited = true)]
    public sealed class MinRequiredPasswordLengthAttribute : ValidationAttribute, IClientValidatable
    {                        
        private readonly int _minimumLength = Membership.MinRequiredPasswordLength;        
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _minimumLength);
        } 
        public override bool IsValid(object value)
        {           
            string password = value.ToString();
            return password.Length >= this._minimumLength;            
        }        
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new[]{
                new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minimumLength, int.MaxValue)
            };
        } 
    }
    

    在您的 ViewModel 上

    [Required]        
    [MinRequiredPasswordLength(ErrorMessage = "The {0} must be at least {1} character(s) long.")]           
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
    

    【讨论】:

      【解决方案2】:

      如果您想为您的验证属性添加可变参数,您需要develop your own attribute 并应用它。

      也许称它为“MinLengthFromConfigFile”?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-26
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-17
        相关资源
        最近更新 更多