/// <summary> /// 确定对象的指定值是否有效。 /// </summary> /// <param name="value"></param> /// <param name="validationContext"></param> /// <returns></returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) { return(base.IsValid(null, validationContext)); } var encodedValue = EncoderHelper.HtmlEncode(value.ToString(), false); if (EncodedStringAndValueAreDifferent(value, encodedValue)) { SetupAllowedStringsDictionary(); foreach (var allowedString in allowedStringsDictionary) { encodedValue = encodedValue.Replace(allowedString.Value, allowedString.Key); } if (EncodedStringAndValueAreDifferent(value, encodedValue)) { return(new ValidationResult(SetErrorMessage(validationContext))); } } if (!string.IsNullOrWhiteSpace(disallowedStrings) && disallowedStrings.Split(',').Select(x => x.Trim()).Any(x => value.ToString().Contains(x))) { return(new ValidationResult(SetErrorMessage(validationContext))); } return(base.IsValid(value, validationContext)); }
private void SetupAllowedStringsDictionary() { if (string.IsNullOrWhiteSpace(allowedStrings)) { return; } foreach (var allowedString in allowedStrings.Split(',').Select(x => x.Trim()) .Where(allowedString => !allowedStringsDictionary.ContainsKey(allowedString))) { allowedStringsDictionary.Add(allowedString, EncoderHelper.HtmlEncode(allowedString, false)); } }