- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我使用 HtmlSanitizer 时没有 DI 它工作得很好。
没有 DI 的 HtmlSanitizer:
但是当我想使用 DI 获取 HtmlSanitizer
时。
我在 Startup.cs 文件中添加了:
services.AddSingleton<IHtmlSanitizer, HtmlSanitizer>();
我使用存储库的构造函数来获取 IHtmlSanitizer
的实例,但是在注入(inject)的 HtmlSanitizer
实例中,AllowedTags
和 AllowAttributes
为空。
带有 DI 的 HtmlSanitizer:
如何使用 DI 获取具有填充属性的 HtmlSanitizer
?
最佳答案
框架正在尝试注入(inject)可选的构造函数参数
public HtmlSanitizer(IEnumerable<string> allowedTags = null, IEnumerable<string> allowedSchemes = null,
IEnumerable<string> allowedAttributes = null, IEnumerable<string> uriAttributes = null, IEnumerable<string> allowedCssProperties = null, IEnumerable<string> allowedCssClasses = null)
{
AllowedTags = new HashSet<string>(allowedTags ?? DefaultAllowedTags, StringComparer.OrdinalIgnoreCase);
AllowedSchemes = new HashSet<string>(allowedSchemes ?? DefaultAllowedSchemes, StringComparer.OrdinalIgnoreCase);
AllowedAttributes = new HashSet<string>(allowedAttributes ?? DefaultAllowedAttributes, StringComparer.OrdinalIgnoreCase);
UriAttributes = new HashSet<string>(uriAttributes ?? DefaultUriAttributes, StringComparer.OrdinalIgnoreCase);
AllowedCssProperties = new HashSet<string>(allowedCssProperties ?? DefaultAllowedCssProperties, StringComparer.OrdinalIgnoreCase);
AllowedAtRules = new HashSet<CssRuleType>(DefaultAllowedAtRules);
AllowedCssClasses = allowedCssClasses != null ? new HashSet<string>(allowedCssClasses) : null;
}
这会导致 DI 容器使用空集合来初始化目标 HtmlSanitizer
类。
在这种情况下,在注册类时使用工厂委托(delegate)并调用构造函数(就像不使用 DI 时所做的那样)
services.AddSingleton<IHtmlSanitizer>(_ => new HtmlSanitizer());
或者简单地创建实例并将其注册到 DI 容器
IHtmlSanitizer sanitizer = new HtmlSanitizer();
services.AddSingleton<IHtmlSanitizer>(sanitizer);
关于c# - HtmlSanitizer + 带有 DI 的 ASP.NET Core 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58065590/
当我尝试使用 Manage Nuget Packages 安装 HtmlSanitizer 时,我收到以下错误消息:无法安装包“HtmlSanitizer 3.2.105”。您正在尝试将此包安装到以“
当我使用 HtmlSanitizer 时没有 DI 它工作得很好。 没有 DI 的 HtmlSanitizer: 但是当我想使用 DI 获取 HtmlSanitizer 时。 我在 Startup.c
我需要在 trix 编辑器中允许带有类的 span 标记。 我可以通过添加span标签来实现 Trix.config.textAttributes.span = { tagName:
我是一名优秀的程序员,十分优秀!