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[中文]</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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With