ASP.NET Core Webアプリケーションで appsettings.json ファイルから設定情報を読み込む - ASP.NET

ASP.NET Core Webアプリケーション(.NET5 .NET6 .NET7)で appsettings.json ファイルから設定情報を読み込むコードを紹介します。

概要

ASP.NET Core Webアプリケーション(ASP.NET 5, ASP.NET 6, ASP.NET 7)では、アプリケーションの設定情報をappsettings.jsonファイルから読み込めます。 この記事では、appsettings.json ファイルからアプリケーションの設定情報を読み込むコードを紹介します。
補足
従来の.NET Framework のASP.NET アプリケーションで設定情報を読み込む場合は Web.Configファイルから読み出すのが一般的な方法です。 .NET Framework のASP.NET アプリケーションで、Web.Configから情報を読み出す方法はこちらの記事を参照してください。

プログラム例

appsettings.json ファイルの編集

ASP.NET 5 プロジェクトを作成するとappsettings.json ファイルがデフォルトで作成されます。


作成直後のappsettings.jsonは下記のコードです。
appsettings.json (アプリケーション作成直後)
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

appsettings.json ファイルにアプリケーションの設定項目を追加します。 今回は "AppConfiguration" セクションを追記し、セクション内に "Value1" "Value2" "Value3" の値を追加しています。
編集後の appsettings.json ファイルは以下のコードです。
appsettings.json (編集後)
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AppConfiguration": {
    "Value1": "Penguin Cookie",
    "Value2": "ぺんぎんクッキー",
    "Value3": "CD-A100"
  }
}

コード

Startup.cs を編集して下記のコードに変更します。
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace AppSettingsAspNetCore
{
  public class Startup
  {
    private readonly IConfiguration _configuration;
    public Startup(IConfiguration configuration)
    {
      _configuration = configuration;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/", async context =>
              {
                context.Response.ContentType = "text/plain; charset=utf-8";

                string value1 = _configuration.GetSection("AppConfiguration")["Value1"];
                string value2 = _configuration.GetSection("AppConfiguration")["Value2"];
                string value3 = _configuration.GetSection("AppConfiguration")["Value3"];

                await context.Response.WriteAsync("Hello World!\r\n");
                await context.Response.WriteAsync("value1:" + value1 + "\r\n");
                await context.Response.WriteAsync("value2:" + value2 + "\r\n");
                await context.Response.WriteAsync("value3:" + value3 + "\r\n");
              });
      });
    }
  }
}

解説

設定ファイルにアクセスするための IConfiguration オブジェクトの処理の記述です。 IConfiguration オブジェクトを保持するメンバ変数を宣言します。
Startup クラスのコンストラクタの引数に IConfiguration オブジェクトの引数を追加します。 IConfiguration オブジェクトは依存関係の挿入 (DI)により引数として受け取れます。
    private readonly IConfiguration _configuration;
    public Startup(IConfiguration configuration)
    {
      _configuration = configuration;
    }
下記コードはコンテンツのエンコーディングとMIMEタイプを指定しています。このコードが無いとWebブラウザでの文字化けが発生します。 詳しくはこちらの記事を参照してください。
context.Response.ContentType = "text/plain; charset=utf-8";

以下のコードでappsettings.json ファイルの値を読み取り変数に代入しています。Startup コンストラクタで受け取った IConfiguration オブジェクトの GetSection() メソッドを呼び出して、AppConfiguration セクションの各値を取得しています。
  string value1 = _configuration.GetSection("AppConfiguration")["Value1"];
  string value2 = _configuration.GetSection("AppConfiguration")["Value2"];
  string value3 = _configuration.GetSection("AppConfiguration")["Value3"];

取得した値をレスポンス情報として出力します。
  await context.Response.WriteAsync("Hello World!\r\n");
  await context.Response.WriteAsync("value1:" + value1 + "\r\n");
  await context.Response.WriteAsync("value2:" + value2 + "\r\n");
  await context.Response.WriteAsync("value3:" + value3 + "\r\n");

実行結果

上記のプロジェクトを実行し、WebブラウザでアプリケーションルートURLにアクセスします。下図の画面が表示されます。
appsettings.jsonファイルに記述された値を読み出して、レスポンス結果に表示できていることが確認できます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2022-10-31
改訂日: 2022-10-31
作成日: 2021-07-15
iPentec all rights reserverd.