简体   繁体   English

HtmlSanitizer + ASP.NET 核心 2 带 DI

[英]HtmlSanitizer + ASP.NET Core 2 with DI

When I use HtmlSanitizer without DI it works well.当我在没有 DI 的情况下使用HtmlSanitizer时效果很好。

HtmlSanitizer without DI:没有 DI 的 HtmlSanitizer:

没有 DI 的 HtmlSanitizer

But when I want to get HtmlSanitizer using DI.但是当我想使用 DI 获取HtmlSanitizer时。

  1. I added to Startup.cs file:我添加到 Startup.cs 文件:

     services.AddSingleton<IHtmlSanitizer, HtmlSanitizer>();
  2. I used constructor of repository to get instance of IHtmlSanitizer but in the injected HtmlSanitizer instance, AllowedTags , and AllowAttributes are empty.我使用存储库的构造函数来获取IHtmlSanitizer的实例,但在注入的HtmlSanitizer实例中, AllowedTagsAllowAttributes是空的。

HtmlSanitizer with DI:带有 DI 的 HtmlSanitizer:

带有 DI 的 HtmlSanitizer

How can I get HtmlSanitizer with filled properties using DI?如何使用 DI 获得具有填充属性的HtmlSanitizer

The frame work is trying to inject the optional constructor parameters框架正在尝试注入可选的构造函数参数

    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 资源

which results in empty collections being used by the DI container to initialize the target HtmlSanitizer class.这导致 DI 容器使用空的 collections 来初始化目标HtmlSanitizer class。

In this case, use the factory delegate when registering the class and call the constructor (just as was done when not using DI)在这种情况下,注册 class 时使用工厂委托并调用构造函数(就像不使用 DI 时所做的那样)

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

Or simply create the instance and register it with the DI container或者简单地创建实例并将其注册到 DI 容器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM