「プロジェクト > 依存関係 > NuGetパッケージの管理」をクリックし、NuGetパッケージから Microsoft.Extensions.Configuration.Json を検索。

Microsoft.Extensions.Configuration.Json をインストール。

ファイル名を appsettings.json にしたJSON ファイルをプロジェクトに追加する。
アプリケーション構成ファイルのファイル名は、 appsettings.json 固定。

appsettings.json のプロパティをクリックし「出力ディレクトリにコピー」は「常にコピーする」に設定する。

appsettings.json のプロパティがデフォルトの「コピーしない」のままだったり、アプリケーション構成ファイル名を appsettings.json 以外にすると下記の例外が発生する。
1 2 3 4 5 6 7 8 |
System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is '・・・\netcoreapp2.0\appsettings.json'. at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload) at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers) at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build() |
appsettings.json に設定した値。
1 2 3 4 5 |
{ "version": "1.0.0-*" } |
appsettings.json を読み込むソースコード。
1 2 3 4 5 6 7 8 9 |
using Microsoft.Extensions.Configuration; var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json"); var Configuration = builder.Build(); var value = Configuration["version"]; |
デバッグ実行でちゃんと読み込めた!

.netcoreのアプリケーション構成ファイルはjsonと言われますが、xmlやiniのライブラリも存在するのでjsonじゃなくても良さそう。

コメント