我希望允许用户将 HTML 发布到站点,但需要确保没有将 Javascript 注入站点。
到目前为止,我已经创建了一个验证属性来检查传入的 html 是否存在狡猾的行为
[AttributeUsage(AttributeTargets.Property,
AllowMultiple = false, Inherited = true)]
public class CheckHtml : ValidationAttribute, IMetadataAware {
private static Regex _check = new Regex(
@"<script[^>]*>.*?<\/script>|<[^>]*(click|mousedown|mouseup|mousemove|keypress|keydown|keyup)[^>]*>",
RegexOptions.Singleline|RegexOptions.IgnoreCase|RegexOptions.Compiled);
protected override ValidationResult IsValid(
object value, ValidationContext validationContext) {
if(value!=null
&& _check.IsMatch(value.ToString())){
return new ValidationResult("Content is not acceptable");
}
return ValidationResult.Success;
}
/// <summary>
/// <para>Allow Html</para>
/// </summary>
public void OnMetadataCreated(ModelMetadata metadata) {
if (metadata == null) {
throw new ArgumentNullException("metadata");
}
metadata.RequestValidationEnabled = false;
}
}
这足够了吗?你怎么做才能检查这种调皮?