htmlsanitizer通过白名单机制严格过滤html:只允许p、a、img标签及href、src等指定属性,未列入allowedtags的标签(如script)整条移除,未列入allowedattributes的属性(如class)即使添加也需同步配置allowedcssclasses才生效。

直接改 HtmlSanitizerOptions 的 AllowedTags 和 AllowedAttributes 就行,但必须注意:不加白名单控制的属性(比如 style 或 onerror)会直接被删,不是“没配就默认放行”。
怎么设置只允许 p、a、img 标签和对应属性
创建实例前传入定制选项,别用无参构造函数:
var options = new HtmlSanitizerOptions
{
AllowedTags = new HashSet<string> { "p", "a", "img" },
AllowedAttributes = new HashSet<string> { "href", "src", "alt", "title" },
AllowedSchemes = new HashSet<string> { "http", "https", "mailto" }
};
var sanitizer = new HtmlSanitizer(options);</string></string></string>
注意三点:
-
AllowedAttributes是全局白名单,不是按标签分组的——src会被同时应用于img和iframe,但后者已被AllowedTags拦截,所以实际只影响img -
href和src这类 URI 属性,必须出现在AllowedSchemes中才生效,否则值会被清空 - 没写进
AllowedTags的标签(比如script、iframe、div)整条标签都会被剥离,不留下内容
为什么加了 class 属性还是不起作用
因为 class 不在默认 AllowedAttributes 里,加了就能用,但仅此不够:
使用 PptxGenJS 和 Python 解析,将结构化的 HTML/CSS 幻灯片内容转换为原生、可编辑的 PowerPoint(.pptx)演示文稿。
- 如果 HTML 里写了
<p class="highlight"></p>,且"highlight"不在AllowedCssClasses中,整个class属性会被删掉(哪怕你开了class) - 想保留特定 class,得同步配置:
options.AllowedCssClasses = new HashSet<string> { "highlight", "note" };</string> - 若想允许任意 class 名(不推荐),可设
options.AllowedCssClasses = null;,但会绕过 CSS 类级安全控制
如何让 data- 自定义属性通过
data- 属性不会被自动识别,必须显式加入 AllowedAttributes:
- 支持通配写法:
options.AllowedAttributes.Add("data-*"); - 也支持单个写法:
options.AllowedAttributes.Add("data-id"); - 注意:通配符只匹配一级,
data-user-id可以,但data-user.profile不行 - 某些版本需启用
options.AllowDataAttributes = true;(检查你用的 NuGet 包版本是否含该属性)
事件钩子比配置更灵活,但容易漏掉关键点
比如你想保留特定 iframe(虽然它不在 AllowedTags 里),可以用 RemovingTag 事件拦截:
sanitizer.RemovingTag += (s, e) =>
{
if (e.Tag.TagName == "iframe")
{
var src = e.Tag.GetAttribute("src");
if (!string.IsNullOrEmpty(src) && src.StartsWith("https://trusted.example.com/"))
{
e.Cancel = true;
}
}
};
但要注意:
- 事件触发时,属性和 URL 已被初步过滤,
e.Tag.GetAttribute("src")返回的是清洗后的值,不是原始输入 -
e.Cancel = true只阻止标签删除,不恢复被删的属性;如果src因协议不符已被清空,这里拿到的就是空字符串 - 这种写法绕过了
AllowedSchemes和AllowedAttributes的统一校验逻辑,后续维护成本高
真正难的不是加标签,而是判断哪些属性要配 scheme、哪些要配 css class、哪些要走通配、哪些必须用事件兜底——这些边界在文档里不显眼,但线上出问题时基本都卡在这几步。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










