原文:asp.net core輸出中文亂碼的問題
摘要
在學習asp.net core的時候,嘗試在控制臺,或者頁面上輸出中文,會出現亂碼的問題。
問題重現
新建控制臺和站點
public class Program{public static void Main(string[] args){ Console.WriteLine("您好,北京歡迎你");Console.Read();}}
站點
public class Startup{// This method gets called by the runtime. Use this method to add services to the container.// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940public void ConfigureServices(IServiceCollection services){}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){loggerFactory.AddConsole();if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.Run(async (context) =>{await context.Response.WriteAsync("您好,北京歡迎你");});}}
那么我們獲取“GB2312”編碼,然后對其編碼呢?
public static void Main(string[] args){Console.WriteLine("您好,北京歡迎你");try{Console.WriteLine(Encoding.GetEncoding("GB2312"));}catch (Exception ex){Console.WriteLine(ex.Message);}Console.Read();}}
'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
上面的大概意思是Encoding 不支持GB2312編碼,需要使用Encoding.RegisterProvider方法進行注冊Provider。
try{Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);Console.WriteLine(Encoding.GetEncoding("GB2312"));}catch (Exception ex){Console.WriteLine(ex.Message);}Console.Read();
CodePagesEncodingProvider在Nuget包System.Text.Encoding.CodePages中
"System.Text.Encoding.CodePages/4.0.1": {"type": "package","dependencies": {"Microsoft.NETCore.Platforms": "1.0.1","System.Collections": "4.0.11","System.Globalization": "4.0.11","System.IO": "4.1.0","System.Reflection": "4.1.0","System.Resources.ResourceManager": "4.0.1","System.Runtime": "4.1.0","System.Runtime.Extensions": "4.1.0","System.Runtime.Handles": "4.0.1","System.Runtime.InteropServices": "4.1.0","System.Text.Encoding": "4.0.11","System.Threading": "4.0.11"},"compile": {"ref/netstandard1.3/System.Text.Encoding.CodePages.dll": {}},"runtimeTargets": {"runtimes/unix/lib/netstandard1.3/System.Text.Encoding.CodePages.dll": {"assetType": "runtime","rid": "unix"},"runtimes/win/lib/netstandard1.3/System.Text.Encoding.CodePages.dll": {"assetType": "runtime","rid": "win"}}},
好了,我們修改下代碼,先注冊,然后輸出中文
try{Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);Console.WriteLine(Encoding.GetEncoding("GB2312"));Console.WriteLine("您好,北京歡迎你");}catch (Exception ex){Console.WriteLine(ex.Message);}
結語
所以在頁面上輸出,或者在控制臺輸出中文的時候,要注意進行注冊Provider。
參考
https://msdn.microsoft.com/zh-cn/library/system.text.encoding.registerprovider(v=vs.110).aspx