Search code examples
c#.netrazorblazorrazor-pages

razor page (blazor) is encoding the characters


I have a little website and when I do Ctrl+U on the website the UTF-8 characters are not being printed correctly.

For example if I try to print programación it prints programación

This is happening only when I print the value of a variable, it does not happen when I hardcode the text.

For example, <div>@variable</div> prints the content with the encoded values like programaci&#xF3;n. But the value itself, using the inspector is programación.

But if in the following line I write <div>programación</div> it prints it correctly.

I tried to use httputlity.htmldecode but I got the same result.

I also tried the meta charset=UTF-8 and I saved the .razor file as UTF. Like it is specified in this post but none of those worked.

Is there any way of printing those characters correctly?

I'm using .NET5 if that matters.


Solution

  • By default, Razor encodes all non-ASCII characters, i.e. those outside of the Basic Latin range. If you want other ranges to be left alone, you need to configure that. You do so in the ConfigureServices method by specifying the ranges that Razor should not encode. The character you are having problems with is in the Latin-1 Supplement range, so you include that:

    services.Configure<WebEncoderOptions>(options =>
    {
        options.TextEncoderSettings = new TextEncoderSettings(
            UnicodeRanges.BasicLatin,
            UnicodeRanges.Latin1Supplement);
    });
    

    Note that whatever you set here will override the default settings, which is why you also need to include the UnicodeRanges.BasicLatin range. If you are unsure which character sets you should include, you can check here: http://www.unicode.org/charts/. Alternatively, you can simply specify UnicodeRanges.All.