LoginSignup
15
13

More than 3 years have passed since last update.

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

Posted at

メモレベルの投稿ですが、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の部分をマッピングする想定です。

public class AzureSettingsModel
{
  AzureStorageSettingsModel Storage { get; set; }
}

public class AzureStorageSettingsModel
{
  public string AccountName { get; set; }
  public string ConnectionString { get; set; }
}

Startup.csにて設定

まずはStartup.csにて値をマッピングします。


public void ConfigureServices(IServiceCollection services)
{
  // Add our Config object so it can be injected
  services.Configure<AzureSettingsModel>(Configuration.GetSection("AzureAppServices"));
}

DIで設定

次は使いたいときに、
下記のようにDIを使って環境ごとに設定された値を取得することができます。


public class IndexModel : PageModel
{
    private readonly IConfiguration _config;

    public IndexModel(IConfiguration config)
    {
        _config = config;
    }

    // The _config local variable is used to obtain configuration 
    // throughout the class.
}

参照

15
13
0

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
15
13