【发布时间】:2011-06-28 07:27:29
【问题描述】:
我希望允许用户将 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;
}
}
这就够了吗? 你如何检查这种调皮?
【问题讨论】:
标签: javascript asp.net-mvc validationattribute