c# - HtmlSanitizer + 带有 DI 的 ASP.NET Core 2

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

当我使用 HtmlSanitizer 时没有 DI 它工作得很好。

没有 DI 的 HtmlSanitizer:

HtmlSanitizer without DI

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

  1. 我在 Startup.cs 文件中添加了:

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

带有 DI 的 HtmlSanitizer:

HtmlSanitizer with DI

如何使用 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;
    }

Source

这会导致 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/

相关文章:

c# - 添加带有 Identity asp.net core 的 UserClaim

android - 在单例私有(private)构造函数类上使用 hilt 进行依赖注入(inject)

c# - 如何在 Linq 中提高此查询性能?

c# - 通知游戏对象发生变化的最佳方式? (Unity脚本组织/委托(delegate))

c# - 整理声音文件

android - Dagger Hilt Android 给出错误 : method getActivityFactory in class DefaultViewModelFactories cannot be applied to given types

具有依赖注入(inject)的 WCF 数据契约设计

c# - Azure API App 客户端不生成枚举

c# - 当涉及不同模型时,如何将主视图和部分 View 值传递给 Controller ​​?

asp.net-core - .net 核心在单一操作方法上覆盖 Controller 级别授权属性