Search code examples
razorencodingcanonical-link

Prevent razor from escaping attributes


We have some links with ü that are getting encoded. So Einführung, for example, gets encoded as:

Einführung

Normally when this happens I can use Html.Raw() to fix it, however it seems that razor doesn't respect Html.Raw() when it's used in our canonical link.

For the title I have:

<title>@Html.Raw(ViewBag.Title)</title>

That works perfectly and does not encode the ü.

For the canonical link I have:

<link rel="canonical" href="@Html.Raw(ViewBag.CanonicalUrl)" />

But this does not prevent it from encoding the ü.

As a test, I tried this:

<link rel="canonical" href="ü" />

And it did not encode it, seemingly confirming that razor is doing this and not some process further down the line.

How do I make it stop?


Solution

  • Apparently it has something to do with it being an attribute, and it must be encoding attributes as a separate step further down the line.

    I was able to fix it by Html.Raw()'ing the entire line like so:

    @Html.Raw("<link rel='canonical' href='" + ViewBag.CanonicalUrl + "' />");
    

    Now it doesn't see it as an attribute so it doesn't try to encode it.