Home > OS >  ASP.NET Core should not encode attribute value in TagBuilder when rendering Json Ld script
ASP.NET Core should not encode attribute value in TagBuilder when rendering Json Ld script

Time:12-09

I wrote an HtmlHelper extension to render Json Ld script tags. The reason why I ask you for help is, the type attribute value "application/ld json" is encoded and looks like "application/ld json" and I could found a solution.

My C# code of the HtmlHelper:

    public static IHtmlContent GetJsonLdScriptTag(this IHtmlHelper helper, string innerText)
    {
        //if(string.IsNullOrEmpty(innerText))
        //    return HtmlString.Empty;

        var tag = new TagBuilder("script");
        tag.MergeAttribute("type", "application/ld json");

        tag.InnerHtml.AppendHtml(innerText);
        tag.TagRenderMode = TagRenderMode.Normal;

        return tag;
    }

In my view I use call the Html extension so:

    @Html.GetJsonLdScriptTag("")

Html output is:

<script type="application/ld&#x2B;json"></script>

I tried to decode by using HtmlDecode(...) and with returning Html.Raw(...);, but without success.

Another try was to return string instead IHtmlContent object, but this failed also.

    public static string GetJsonLdScriptTag(this IHtmlHelper helper, string innerText)
    {
        //if(string.IsNullOrEmpty(innerText))
        //    return HtmlString.Empty;

        var tag = new TagBuilder("script");
        tag.MergeAttribute("type", "application/ld json");

        tag.InnerHtml.AppendHtml(innerText);
        tag.TagRenderMode = TagRenderMode.Normal;

        return tag.ToHtmlString();
    }

    public static string ToHtmlString(this IHtmlContent content)
    {
        using var writer = new IO.StringWriter();
        content.WriteTo(writer, HtmlEncoder.Default);
        return writer.ToString();
    }

Do you have an idea to handle this issue without hacks?

Best Tino

CodePudding user response:

Looking at the source code, there doesn't seem to be any way to disable the encoding for an attribute value. It might be worth logging an issue to see if this could be added; but for the short term, you'll need to use something other than the TagBuilder class.

private sealed class JsonLdScriptTag : IHtmlContent
{
    private readonly string _innerText;
    
    public JsonLdScriptTag(string innerText)
    {
        _innerText = innerText;
    }
    
    public void WriteTo(TextWriter writer, HtmlEncoder encoder)
    {
        writer.Write(@"<script type=""application/ld json"">");
        writer.Write(_innerText);
        writer.Write("</script>");
    }
}

public static IHtmlContent GetJsonLdScriptTag(this IHtmlHelper helper, string innerText)
    => new JsonLdScriptTag(innerText);
  • Related