メモレベルの投稿ですが、appsettings.json
の使い方
環境
- Visual Studio
- C# ASP.NET CORE
appsettings.json
とは
文字のごとく、アプリの設定ファイルになります。開発環境、テスト環境、本番環境などで参照するサーバーやサービスを変更したいときに使います。
appsettings.json
をローカル環境に利用appsettings.Development.json
を開発環境に利用
とわけることができます。
Azure Web App
を使っている場合は、サーバー側でも設定することができます。
利用方法
appsettings.jsonを編集
下記のようになappsettings.json
を保存します。これで各環境にあったアカウントに接続します。
{"ConnectionStrings":{"DefaultConnection":"ここにコネクション文字列"},"Logging":{"LogLevel":{"Default":"Information","Microsoft":"Warning","Microsoft.Hosting.Lifetime":"Information"}},"AllowedHosts":"*","AzureAppServices":{"Storage":{"AccountName":"ここにアカウント名","ConnectionString":"ここに接続文字列"}}}
クラスを定義
先ほど編集したappsetting.jsonを受けるクラスを定義します
AzureKeysの部分をマッピングする想定です。
publicclassAzureSettingsModel{ AzureStorageSettingsModelStorage{get;set;}}publicclassAzureStorageSettingsModel{publicstringAccountName{get;set;}publicstringConnectionString{get;set;}}
Startup.csにて設定
まずはStartup.csにて値をマッピングします。
publicvoidConfigureServices(IServiceCollectionservices){// Add our Config object so it can be injectedservices.Configure<AzureSettingsModel>(Configuration.GetSection("AzureAppServices"));}
DIで設定
次は使いたいときに、
下記のようにDIを使って環境ごとに設定された値を取得することができます。
publicclassIndexModel:PageModel{privatereadonlyIConfiguration_config;publicIndexModel(IConfigurationconfig){_config=config;}// The _config local variable is used to obtain configuration // throughout the class.}
参照
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1