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

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

概要

Razor Pagesでappsettings.json ファイルから設定情報を読み込む場合は、DIを利用します。

プログラム : Razor Pages でページモデルを利用する場合

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;

namespace AppSettingsAspNetRazorPages
{
  public class Startup
  {
    // 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)
    {
      services.AddRazorPages();
    }

    // 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.MapRazorPages();
      });
    }
  }
}
test-01.cshtml
@page
@model AppSettingsAspNetRazorPages.Pages.test_01Model
@{
}
<html>
<head>

</head>
<body>
  <h2>appsettings.jsonのデモ</h2>
  <p>@Model.value1</p>
  <p>@Model.value2</p>
  <p>@Model.value3</p>
</body>
</html>
test-01.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;

namespace AppSettingsAspNetRazorPages.Pages
{
  public class test_01Model : PageModel
  {
    public string value1 { get; set; }
    public string value2 { get; set; }
    public string value3 { get; set; }
    private readonly IConfiguration _conf;

    public test_01Model(IConfiguration configuration)
    {
      _conf = configuration;      
    }

    public void OnGet()
    {
      value1 = _conf.GetSection("AppConfiguration")["value1"];
      value2 = _conf.GetSection("AppConfiguration")["value2"];
      value3 = _conf.GetSection("AppConfiguration")["value3"];
    }
  }
}
appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AppConfiguration": {
    "value1": "ぺんぎんクッキー",
    "value2": "Penguin Cookie",
    "value3": "250円"
  }
}

解説

ページモデルクラスを利用する場合、ページモデルクラスのコンストラクタに IConfdiguration オブジェクトの引数を追加します。
ページモデルのクラスの作成時に、IConfigurationオブジェクトが渡されますので、ページモデルのメンバ変数に渡された、IConfiguration オブジェクトを代入して保存します。
    private readonly IConfiguration _conf;

    public test_01Model(IConfiguration configuration)
    {
      _conf = configuration;      
    }

appsettings.json からの値の取得は、OnGet メソッド内で実行します。
コンストラクタで保持した、IConfigurationオブジェクトのGetSction() メソッドを呼び出してappsettings.jsonの値を取得しページモデルクラスのプロパティに代入します。
  public string value1 { get; set; }
  public string value2 { get; set; }
  public string value3 { get; set; }

  public void OnGet()
  {
    value1 = _conf.GetSection("AppConfiguration")["value1"];
    value2 = _conf.GetSection("AppConfiguration")["value2"];
    value3 = _conf.GetSection("AppConfiguration")["value3"];
  }

ページへの表示はRazor Page内で @Model でページモデルクラスを参照しプロパティの値をページ内に表示します。
<body>
  <h2>appsettings.jsonのデモ</h2>
  <p>@Model.value1</p>
  <p>@Model.value2</p>
  <p>@Model.value3</p>
</body>

実行結果

上記のプロジェクトを実行します。Webブラウザで、(アプリケーションルートURL)/test-01 のURLにアクセスします。下図のページが表示されます。
appsettings.jsonに設定された値を読み出してRazor Page に表示できていることが確認できます。

プログラム : Razor Pages でページモデルを利用しない場合

ページモデルを利用しない場合のコード例です。

コード

先ほどのプログラム例と同じプロジェクトとコードを準備します。 Pagesフォルダ内に新しいRazor Page を作成します。
test-02.cshtml.cs
@page
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
@{
}
<html>
<head>

</head>
<body>
  <h2>appsettings.jsonのデモ2</h2>
  <p>@Configuration.GetSection("AppConfiguration")["value1"]</p>
  <p>@Configuration.GetSection("AppConfiguration")["value2"]</p>
  <p>@Configuration.GetSection("AppConfiguration")["value3"]</p>
</body>
</html>

解説

RazorPage内で、IConfiguration オブジェクトを扱うため、@using キーワードを利用して Microsoft.Extensions.Configuration の参照を追加します。
@using Microsoft.Extensions.Configuration

ページモデルクラスを利用している場合は、ページモデルクラスのコンストラクタにIConfiguration オブジェクトの引数を追加しましたが、 Razor Pageの場合は、@inject キーワードを利用します。
以下のコードでは、IConfiguration オブジェクトを Configuration 変数に設定しています。
@inject IConfiguration Configuration

appsettings.json の値は、Configurationオブジェクトの GetSection メソッドを呼び出して取得し、Razor Pageに表示します。
<body>
  <h2>appsettings.jsonのデモ2</h2>
  <p>@Configuration.GetSection("AppConfiguration")["value1"]</p>
  <p>@Configuration.GetSection("AppConfiguration")["value2"]</p>
  <p>@Configuration.GetSection("AppConfiguration")["value3"]</p>
</body>

実行結果

上記のプロジェクトを実行します。Webブラウザで、(アプリケーションルートURL)/test-02 のURLにアクセスします。下図のページが表示されます。
appsettings.jsonに設定された値を読み出してRazor Page に表示できていることが確認できます。


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