返回文章列表

从Razor标记呈现HTML时,中文字符在“查看页面源代码”中不能正常显示

2025-08-21

问题描述:从Razor标记呈现HTML时,中文字符被转换为NCR(数值字符引用),即一系列以“&#”或“&#x”开头的值。

NCR(Numeric Character Reference,数值字符引用)是一种在 HTML 、XML 等标记语言中表示特殊字符的编码方式,以“&#x”(表示16进制编码)或“&#”(表示10进制编码)开头,后跟字符的Unicode编码值,以分号结尾。

例如:Razor标记

<p>@("中文字符串")</p>

在页面源代码中显示为

<p>&#x4E2D;&#x6587;&#x5B57;&#x7B26;&#x4E32;</p>

原因:默认情况下,编码器使用限制为基本拉丁语Unicode范围的安全列表,会将该范围之外的所有字符都编码为其字符代码等效项。

解决方法:在Program.cs中,可以自定义编码器安全列表,以在启动期间添加适用于应用的Unicode范围:

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

将安全列表扩大到包含Unicode范围CjkUnifiedIdeographs。页面源代码中会变为

<p>中文字符串</p>

参考链接:自定义编码器

An unhandled error has occurred. Reload 🗙

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please retry or reload the page.