简体   繁体   中英

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?

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>

Issue :

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM