【问题标题】:Setting ASP.NET Core TagHelper Attribute Without Encoding在不编码的情况下设置 ASP.NET Core TagHelper 属性
【发布时间】:2016-06-10 19:36:25
【问题描述】:

我想将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";
    }
}

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

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

如何阻止这种编码发生?

【问题讨论】:

    标签: asp.net razor asp.net-core asp.net-core-mvc tag-helpers


    【解决方案1】:

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

    解决方案基本上是您自己创建TagHelperAttribute 类,而不是简单地分配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

    【讨论】:

    • 这适用于属性但不适用于标签内容。
    • @LordofScripts:对于标签内容,您有 output.Content.Append(string unencoded)output.Content.AppendHtml(new HtmlString("mystring&amp;somethingelse")
    • 谢谢,现在才弄明白,准备发帖更新。太好了!
    • 帮助很大。 HtmlString 工作得很好 - 使用 .NET Core 2.0。
    • 或者直接使用output.Attributes.SetAttribute(IntegrityAttributeName, new HtmlString(...))
    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多