Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9364

[ASP.NET] appsettings.jsonの使い方

$
0
0

メモレベルの投稿ですが、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


Viewing all articles
Browse latest Browse all 9364

Latest Images

Trending Articles