有園友在博問中提了這樣一個問題 —— .NET Core 中文等非英文文字html編碼輸出問題,到我們的 ASP.NET Core 項目中一看,也是同樣的問題。
比如下面的Razor視圖代碼:
@{ ViewBag.Title = "代碼改變世界"; } <title>@ViewBag.Title</title>
輸出的html代碼變成了:
<title>代码改变世界</title>
上面的 @ViewBag.Title 實際上等同於下面的代碼:
@Html.Raw(Html.Encode(ViewBag.Title))
所以解決這個問題需要從ASP.NET Core MVC中的HtmlHelper下手(上面代碼中Html的類型就是HtmlHelper)。
從GitHub上簽出MVC的源代碼看看HtmlHelper.Encode()的實現:
private readonly IHtmlGenerator _htmlGenerator; public string Encode(string value) { return _htmlGenerator.Encode(value); }
實際調用的是IHtmlGenerator接口的Encode()方法,MVC中實現這個接口的是DefaultHtmlGenerator,其對應的Encode()實現代碼如下:
private readonly HtmlEncoder _htmlEncoder; public string Encode(string value) { return !string.IsNullOrEmpty(value) ? _htmlEncoder.Encode(value) : string.Empty; }
原來真正干活的主角是HtmlEncoder,但它不是在MVC中實現的,而是在.NET Core Framework中實現的,命名空間是 System.Text.Encodings.Web 。
寫個.NET Core控制台程序直接調用HtmlEncoder看看是不是就是它惹的禍。
public class Program { public static void Main(string[] args) { Console.WriteLine(HtmlEncoder.Default.Encode("代碼改變世界")); } }
輸出結果與MVC中是同樣的問題。
試試不用默認的HtmlEncoder實例(HtmlEncoder.Default),而是自己調用HtmlEncoder.Create()方法創建實例,這時發現了UnicodeRange參數類型。
public static HtmlEncoder Create(params UnicodeRange[] allowedRanges);
當使用UnicodeRanges.All作為參數創建HtmlEncoder實例時,問題就解決了。
Console.WriteLine(HtmlEncoder.Create(UnicodeRanges.All).Encode("代碼改變世界"));
緊接着從GitHub上簽出System.Text.Encodings.Web的源代碼,看看HtmlEncoder.Default對應的HtmlEncode實例是如何被創建的:
internal readonly static DefaultHtmlEncoder Singleton = new DefaultHtmlEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin));
原來用的是UnicodeRanges.BasicLatin,難怪中文會被編碼,搞不懂為什么默認不用UnicodeRanges.All?
知道了問題的原因,解決起來就不難了,只要我們以HtmlEncoder.Create(UnicodeRanges.All)創建HtmlEncoder實例,並替換掉MVC中所用的默認HtmlEncoder實例。那如何替換呢?
回到MVC的源代碼中,看看DefaultHtmlGenerator的實現,發現它的構造函數參數中有HtmlEncoder:
public DefaultHtmlGenerator( IAntiforgery antiforgery, IOptions<MvcViewOptions> optionsAccessor, IModelMetadataProvider metadataProvider, IUrlHelperFactory urlHelperFactory, HtmlEncoder htmlEncoder, ClientValidatorCache clientValidatorCache) { }
根據.NET從上到下、由內而外全面依賴注入的秉性,這個地方應該也是依賴注入的,我們只需注入一個新的HtmlEncoder實例即可,是不是這樣呢?
碼上一行,你就知道。
在 Startup.cs 的 ConfigureServices() 方法中添加下面的一行代碼:
services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
運行ASP.NET Core站點,輸出結果如下:
<title>代碼改變世界</title>
一行注入,立馬解決。依賴注入的威力,.NET Core的魅力。
更新1:根據 零度的火 的評論,更好的解決方法是
services.Configure<WebEncoderOptions>(options => { options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All); });
更新2:后來發現更好的解決方法
services.Configure<WebEncoderOptions>(options => options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs));