只有累積,沒有奇蹟

2019年3月9日 星期六

[.NETCore] ASP.Net Core 使用 Big5 中文編碼

問題
在 .NET Framework 時要取得中文編碼可以使用  Encoding.GetEncoding("BIG5"),今天在練習專案時遇到類似的情境很直覺的在將 Code 套用在 .NET Core 上,沒想到竟然發生錯誤,這邊簡單紀錄遇到這問題該怎麼解決以及根本原因,有任何問題歡迎留言一起討論

解決方式
 "ArgumentException: 'Big5' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.  錯誤訊息明確的提到不支援 big5 編碼,心理OS是為什麼在 .NET Framework 使用很正常為啥在 .NET Core 就異常了呢 ? 因此第一步是先好奇在 .NET Core 所支援的編碼到底有哪幾,透過以下代碼,可以得知目前在 .Core 2.1 中支援的編碼有那些
private static void GetEncodingInfos()
{
    var encodings = Encoding.GetEncodings();

    foreach (var t in encodings)
    {
        Console.WriteLine($"DisplayName:{t.DisplayName}, codePage: {t.CodePage}");
    }
}
輸出結果如下,可以得知目前  .NET Core 2.1 內建支援 8 種編碼方式  
NETCoreLogging> DisplayName:Unicode, codePage: 1200
NETCoreLogging> DisplayName:Unicode (Big-Endian), codePage: 1201
NETCoreLogging> DisplayName:Unicode (UTF-32), codePage: 12000
NETCoreLogging> DisplayName:Unicode (UTF-32 Big-Endian), codePage: 12001
NETCoreLogging> DisplayName:US-ASCII, codePage: 20127
NETCoreLogging> DisplayName:Western European (ISO), codePage: 28591
NETCoreLogging> DisplayName:Unicode (UTF-7), codePage: 65000
NETCoreLogging> DisplayName:Unicode (UTF-8), codePage: 65001
稍微爬了文章後發現在 .NET Core 專案不在支援像是 .NET Framework 一脫拉庫的編碼方式,僅支援常用的八種,有需要可以透過下載取得;這時回想到上課時講師也提過 .NET Core 設計思考方向是精簡化保留最核心的 API,其他 API 如果要用的時候在透過 Nuget 的方式下載即可,也就是需要時甚麼在下載/安裝相關套件或是 library,而不是全部包起來同捆包的概念;知道想要的中文編碼 BIG5 不支援已經是事實,要使用就要先安裝 system.text.encoding.codepages,以下為安裝說明

安裝 System.Text.Encoding.CodePages 
如上面提到,如果需要更多編碼需要透過 nuget 進行下載  System.Text.Encoding.CodePages 套件,因此開啟 Nuget packer Manager 輸入System.Text.Encoding.CodePages,目前提供版本為 4.5.1 點擊下載
或是直接在 package console 輸入下列代碼  
Install-Package System.Text.Encoding.CodePages -Version 4.5.1

註冊 EncodingProvider
安裝完成之後不會自動支援內建之外的編碼,需要在透過下列代碼來設定
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.RegisterProvider 
註冊 encoding provider,此方法提供讓開發者可以註冊在目標平台不支援的編碼方式  CodePagesEncodingProvider.Instance 
Instance 屬性會回傳 Encoding provider 物件

重新驗證
如上述所提到修改範圍,最後代碼如下
static void Main(string[] args)
{
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    var big5 = Encoding.GetEncoding(950);
    Console.WriteLine($"Name : {big5.EncodingName} , CodePage :{big5.CodePage}");
    Console.ReadKey();
}
執行程式後結果
順利過關,打完收工

參考
难道.NET Core到R2连中文编码都不支持吗?

0 意見:

張貼留言

Copyright © m@rcus 學習筆記 | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com