更新(2020 年 2 月):
微软的 AntiXSS 库在其 Sanitizer 类上包含一个名为 GetSafeHtmlFragment 的静态方法,该方法似乎可以完成此任务。 (建议来自@exploring.cheerily.impresses)
在 .NET 4.5+ 中或通过添加System.Web.Security.AntiXss
对于旧版本的.NET,有一个很好的方法来解决这个问题。我们可以用[AllowHtml]
和自定义注释属性在一起。该方法应将字符串内的 HTML 标记列入白名单并验证请求。
以下是此作业的自定义注释属性:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
public sealed class RemoveScriptAttribute : ValidationAttribute
{
public const string DefaultRegexPattern = @"\<((?=(?!\b(a|b|i|p)\b))(?=(?!\/\b(a|b|i|p)\b))).*?\>";
public string RegexPattern { get; }
public RemoveScriptAttribute(string regexPattern = null)
{
RegexPattern = regexPattern ?? DefaultRegexPattern;
}
protected override ValidationResult IsValid(object value, ValidationContext ctx)
{
var valueStr = value as string;
if (valueStr != null)
{
var newVal = Regex.Replace(valueStr, RegexPattern, "", RegexOptions.IgnoreCase, new TimeSpan(0, 0, 0, 0, 250));
if (newVal != valueStr)
{
var prop = ctx.ObjectType.GetProperty(ctx.MemberName);
prop.SetValue(ctx.ObjectInstance, newVal);
}
}
return null;
}
}
然后你应该使用 [AllowHtml] 和 [RemoveScript] 属性来装饰你想要 HTML 的模型属性,如下所示:
public class MyModel
{
[AllowHtml, RemoveScript]
public string StringProperty { get; set; }
}
这将只允许 、、 和 html 标签获取它。所有其他标签都将被删除,但它足够智能,可以保留标签的内部文本。例如。如果您发送:
“这是John Smith输入的富文本。”
你最终会得到这个:
“这是 John Smith 输入的富文本。”
将更多 HTML 标签列入白名单也很容易。例如。如果你想接受,
和
,更改
DefaultRegexPattern
(影响全局)或将修改后的 regexPattern 传递给实例
RemoveScriptAttribute
, 像这样:
[AllowHtml]
[RemoveScript(regexPattern: @"\<((?=(?!\b(a|b|i|p|u|br|hr)\b))(?=(?!\/\b(a|b|i|p|u)\b))).*?\>")]
public string Body { get; set; }