LoginSignup
7
8

More than 3 years have passed since last update.

ASP.NET Core 3.1 MVC における構成ファイル appsettings.json からの値取得

Posted at

はじめに

以前の以下の投稿で、.NET Core 1.1 での ASP.NET Core において appsettings.json からの値取得の方法を説明しました。

今回は、.NET Core 3.1 での ASP.NET Core において、appsettings.json からの値取得の方法を説明します。
基本的な方法はほとんど同じです。

appsettings.json の定義

appsettings.json を以下のように定義したとします。

appsettings.json
{
  "UserSettings": {
    "IsDemoMode": false,
    "DefaultUser": {
      "Name": "足利 義教",
      "Age": 48
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

IConfiguration での構成情報の取得

何もしなくても構成情報は、依存性の注入がされているので、コントローラーから、構成情報を IConfiguration で取得できます。

HomeController.cs

public class HomeController : Controller
{
    private readonly IConfiguration _configuration;
    private readonly ILogger<HomeController> _logger;


    public HomeController(IConfiguration configuration, ILogger<HomeController> logger)
    {
            this._configuration = configuration;            
            this._logger = logger;
    }

    public IActionResult Index()
    {   
        //ブール値のロード
        bool isDemoMode = this._configuration.GetValue<bool>("UserSettings:IsDemoMode");
        //文字列値のロードは、インデクサで指定可能
        string defaultUserName = this._configuration["UserSettings:DefaultUser:Name"];
        //int 値のロード
        int defaultUserAge = this._configuration.GetValue<int>("UserSettings:DefaultUser:Age");

        return View((isDemoMode, defaultUserName, defaultUserAge));
    }

    ...
}

オプション パターンでの構成情報の取得

前回の記事でも触れましたが、構成情報をクラスにバインドして、そこから取得した方が可読性があがりますね。

JSON の定義に対応するクラスを定義します。
前回も説明しましたが、Visual Studio からクラス ファイルを追加し、JSON ファイルの文字列をコピーして、[編集] - [形式を選択して貼り付け] - [JSON をクラスとして貼り付ける] を選択すると、クラスの定義をペースト出来るので便利です。

UserSettings.cs

    public class UserSettings
    {
        public bool IsDemoMode { get; set; }
        public DefaultUser DefaultUser { get; set; }
    }

    public class DefaultUser
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

次に、StartUp.ConfigureServices からサービス コレクション経由で構成情報を注入します。

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //構成情報の注入
        services.Configure<UserSettings>(this.Configuration.GetSection("UserSettings"));
        services.AddControllersWithViews();            
    }

    ...
}

これで、コントローラーから、注入した構成情報を取得できます。

HomeController.cs

public class HomeController : Controller
{
    private readonly UserSettings _userSettings;

    private readonly ILogger<HomeController> _logger;        

    public HomeController(IOptions<UserSettings> userSettings, ILogger<HomeController> logger)
    {
        //構成情報の取得
        this._userSettings = userSettings.Value;
        this._logger = logger;
    }

    public IActionResult Index()
    {
        //構成情報の参照
        return View(this._userSettings);
    }

    ...
}

固有のクラス経由で構成情報を取得した方が、やはり可読性があがりますね。

参考サイト

7
8
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
7
8