Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop ASP.NET Core 2 MVC's razor engine using HTML unicode escaping?

Create a default ASP.NET Core 2 MVC project normally, then modify the action a little:

public IActionResult About()
{
    ViewData["Message"] = "This is Chinese[中文]";
    return View();
}

And this is the view (About.cshtml):

<h3>@ViewData["Message"]</h3>
<h3>这也是中文</h3>

This is the output result in browser:

<h3>This is Chinese[&#x4E2D;&#x6587;]</h3>
<h3>这也是中文</h3>

I found that the Chinese text rendered by the '@' sign is html unicode escaped. The question is how to stop the '@' sign to escape my text?

like image 821
guogangj Avatar asked Mar 19 '18 15:03

guogangj


2 Answers

According to this article:

By default encoders use a safe list limited to the Basic Latin Unicode range and encode all characters outside of that range as their character code equivalents. This behavior also affects Razor TagHelper and HtmlHelper rendering as it will use the encoders to output your strings.

The article also provides a proper way to customize default html encoder. Add following registration to Startup.ConfigureServices method:

services.AddSingleton<HtmlEncoder>(
    HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
        UnicodeRanges.CjkUnifiedIdeographs }));

Here is result html code after this adjustment:

<h3>This is Chinese[中文]</h3>
<h3>这也是中文</h3>
like image 62
CodeFuller Avatar answered Oct 22 '22 09:10

CodeFuller


Issue:

DotNet Core Controller is returning HTML that is not being rendered correctly because the HTML is being ESCAPED.

Caveat: It should be noted the 'auto escaping' performed by the framework is for safety issues to avoid unwanted or dangerious html being injected.

Answer:

@Html.Raw(ViewData["Message"])

Rational

When Razor calls custom functions that create HTML, the HTML that is returned is typically automatically escaped. This is by design and is not uncommon to many frameworks (like Rails). Anyway, the OUTPUT that custom function returns must be rendered as RAW.

like image 42
FlyingV Avatar answered Oct 22 '22 08:10

FlyingV