我想添加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";
}
}
这是上面代码的输出,其中+
已被替换为+
:
<script integrity="sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7"></script>
我怎样才能阻止这种编码的发生?
提供的代码对我不起作用,因为ProcessAsync
方法没有被调用。这有一些问题(抽象类无法实例化,没有script
属性等)。
解决方案基本上是您创建TagHelperAttribute
自己分类,而不是简单地分配string
type.
@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
.
在《剃刀》中,string
s会自动逃脱。如果你想避免转义,你必须使用HtmlString
反而。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)