Hello @mc,
Thanks for your question! What you're observing is HTML encoding of Unicode characters, which is a normal and expected behavior in ASP.NET MVC when rendering content to the browser.
Why This Happens:
ASP.NET Core uses automatic HTML encoding when rendering content via Razor syntax (e.g., @ViewData["Title"]). This is a security feature designed to prevent Cross-Site Scripting (XSS) attacks by ensuring that any potentially unsafe characters are encoded before being sent to the browser.
For example:
ViewData["Title"] = "首页";
When rendered in Razor:
<h1>@ViewData["Title"]</h1>
The output HTML might look like:
<h1>首页</h1>
This is the Unicode HTML entity representation of "首页", and browsers will correctly decode and display it as the intended characters.
If you're seeing the encoded form in the browser source code, that's expected. But if you're seeing the encoded form on the actual page, then you might be double-encoding the content or using Html.Raw() incorrectly.
To render raw HTML (only if you're sure the content is safe), you can use:
<h1>@Html.Raw(ViewData["Title"])</h1>
Important: Use Html.Raw() cautiously, especially with user-generated content, as it bypasses HTML encoding and can expose your app to XSS vulnerabilities.
Here's a bit more context: in ASP.NET Core, you have an option to control this behavior. By default, the encoders are set to allow only a safe list of characters. If your application often uses non-Latin characters (like Chinese), you might consider customizing the encoder to include additional Unicode ranges.
To do this, you can modify your Program.cs file to include the ranges that suit your application. Here’s an example of how to widen the encoder's safe list to include Chinese characters:
builder.Services.AddSingleton<HtmlEncoder>(
HtmlEncoder.Create(allowedRanges: [ UnicodeRanges.BasicLatin,
UnicodeRanges.CjkUnifiedIdeographs ]));
This adjustment will allow for process-rendering of characters like "首页" without encoding them into their Unicode escape representations.
I hope that my answer helps you clarify your issue.