在不编码的情况下设置 ASP.NET 核心 TagHelper 属性

Setting ASP.NET Core TagHelper Attribute Without Encoding

我想将 integrity 属性添加到我的标签助手中的脚本标签。它包含一个我不想编码的 + 符号。

<script integrity="sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7"></script>

这是我的标签助手:

[HtmlTargetElement(Attributes = "script")]
public class MyTagHelper : TagHelper
{
    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        // Omitted...

        output.Attributes["integrity"] = "sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7";
    }
}

这是上面代码的输出,其中 + 已被 &#x2B; 替换:

<script integrity="sha384-Li9vy3DqF8tnTXuiaAJuML3ky&#x2B;er10rcgNR/VqsVpcw&#x2B;ThHmYcwiB1pbOxEbzJr7"></script>

如何阻止这种编码发生?

提供的代码对我不起作用,因为未调用 ProcessAsync 方法。这有一些问题(抽象 class 无法实例化,没有 script 属性等)。

解决方案基本上是您自己创建 TagHelperAttribute class,而不是简单地分配 string 类型。

@section Scripts {
    <script></script>
}

标签助手

[HtmlTargetElement("script")]
public class MyTagHelper : TagHelper
{
    public const string IntegrityAttributeName = "integrity";
    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        // Omitted...

        output.Attributes[IntegrityAttributeName] = new TagHelperAttribute(IntegrityAttributeName, new HtmlString("sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7"));

        await Task.FromResult(true);
    }
}

这会正确输出

<script integrity="sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7"></script>

原因是,TagHelperAttribute 对隐式 (=) 运算符有一个运算符重载 public static implicit operator TagHelperAttribute(string value),它将创建 TagHelperAttribute 并传递字符串,因为它是 Value.

在 Razor 中,strings 会自动转义。如果您想避免转义,则必须改用 HtmlString