【问题标题】:HtmlSanitizer + ASP.NET Core 2 with DIHtmlSanitizer + 带有 DI 的 ASP.NET Core 2
【发布时间】:2020-01-23 17:01:57
【问题描述】:

当我在没有 DI 的情况下使用 HtmlSanitizer 时效果很好。

没有 DI 的 HtmlSanitizer:

但是当我想使用 DI 获取 HtmlSanitizer 时。

  1. 我添加到 Startup.cs 文件中:

    services.AddSingleton<IHtmlSanitizer, HtmlSanitizer>();
    
  2. 我使用存储库的构造函数来获取IHtmlSanitizer 的实例,但是 在注入的HtmlSanitizer 实例中,AllowedTagsAllowAttributes 为空。

带有 DI 的 HtmlSanitizer:

如何使用 DI 获得具有填充属性的 HtmlSanitizer

【问题讨论】:

  • 查看this blog post 的“框架类型”部分。它为@Nkosi 的回答提供了一般建议。

标签: c# asp.net-core dependency-injection html-sanitizing


【解决方案1】:

框架正在尝试注入可选的构造函数参数

    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;
    }

Source

这会导致 DI 容器使用空集合来初始化目标 HtmlSanitizer 类。

在这种情况下,注册类时使用工厂委托并调用构造函数(就像不使用DI时所做的那样)

services.AddSingleton<IHtmlSanitizer>(_ => new HtmlSanitizer());

或者简单地创建实例并将其注册到 DI 容器中

IHtmlSanitizer sanitizer = new HtmlSanitizer();
services.AddSingleton<IHtmlSanitizer>(sanitizer);

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2023-04-03
    • 2017-08-03
    • 2017-07-28
    • 2020-06-09
    • 2018-11-14
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多