LoginSignup
7
2

More than 3 years have passed since last update.

ASP.NET CoreでShift_JISでCSV出力しようとしたら他ページのHTMLの中身が空になった件

Last updated at Posted at 2019-09-05

.NET Coreは標準ではShift_JISに対応していない

顧客要件でShift_JISでのCSVファイル出力をする必要があったので単純にStreamWriterに
System.Text.Encoding.GetEncoding("shift_jis")
を指定すればOKかと思ったらエラーを吐いた。

System.ArgumentException: 'shift_jis' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
   at System.Text.EncodingTable.GetCodePageFromName(String name)
   at System.Text.Encoding.GetEncoding(String name)

shift_jisがサポートされていない……だと……

ちょろっと調べたら.NET CoreではASCIIとUnicodeしか標準ではサポートしていないらしい
Windows10でも標準文字コードをShift_JISからUTF-8に置き換えてるらしいからその一環だろう

他の文字コード使いたいならCodePagesEncodingProviderを使う

nugetでSystem.Text.Encoding.CodePagesを追加すればOK
スクリーンショット 2019-08-31 11.04.51.png

そしてShift_JIS使うコードの前で下記を呼び出せばOK

// エンコードプロバイダを登録
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

……のはずだったのだが

HTMLレスポンスのBody部が空で返ってくる現象が発生

System.Text.Encoding.CodePagesを追加した以外コードをひとつも弄っていない状態でも何故か空のHTMLページがレスポンスとして返ってくる

解決方法

Program.csMainメソッドでエンコードプロバイダを登録すればOK

public static void Main(string[] args)
{
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    CreateWebHostBuilder(args).Build().Run();
}

ここで登録しておけばShift_JIS使う直前に再度登録する必要も無いのでASP.NET Coreで標準文字コード以外使う時はMainメソッド内でエンコードプロバイダ登録と覚えておけばよい

7
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2