设置ASP.NET核心TagHelper属性不进行编码 [英] Setting ASP.NET Core TagHelper Attribute Without Encoding

查看:251
本文介绍了设置ASP.NET核心TagHelper属性不进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在完整属性添加到脚本标记在我的标签帮手。它包含我不想带$ C $光盘 + 标志。

I want to add the integrity attribute to a script tag in my tag helper. It contains a + sign which I don't want encoded.

<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";
    }
}

这是上面code,其中 + 已取代&放大器的输出;#X2B;

This is the output of the above code, where + has been replaced by &#x2B;:

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

如何从发生停止此编码?

How can I stop this encoding from taking place?

推荐答案

所提供的code并没有为我工作,因为 ProcessAsync 方法不调用。有一些事情不对的(抽象类不能被实例化,就没有剧本属性等)。

The provided code didn't work for me, as the ProcessAsync method wasn't called. There were some things wrong with this (abstract class can't be instantiated, there is no script attribute etc.).

该解决方案基本上是你创建 TagHelperAttribute 自己的类,而不是简单地分配字符串键入。

The solution is basically that you create the TagHelperAttribute class yourself, instead of simply assigning the 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 有一个运算符重载公共静态隐运营商TagHelperAttribute(字符串值)对于隐式的( = )运算符,它会创建 TagHelperAttribute 并通过字符串作为它的

The reason for this is, that TagHelperAttribute has an operator overload public static implicit operator TagHelperAttribute(string value) for the implicit (=) operator, which will create the TagHelperAttribute and pass the string as it's Value.

在剃刀,字符串取值都会自动转义。如果你想避免逃逸,你必须使用 HtmlString 来代替。

In Razor, strings get escaped automatically. If you want to avoid the escaping, you have to use HtmlString instead.

这篇关于设置ASP.NET核心TagHelper属性不进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆