ASP.NET アプリケーションで appsetting.json の参照ファイルをデバッグ、リリースで切り替える方法を紹介します。
概要
ASP.NET アプリケーションでデバッグ時とリリース時でappsettings.json を変更する方法を紹介します。
この記事では、launchSettings.jsonにプロファイルを追加して切り替える方法と、プリプロセッサ ディレクティブを利用する2通りの切り替え方法を紹介します。
プロファイルで切り替える方法
ASP.NETアプリケーション起動時のプロファイルでappsettings.jsonを切り替える方法です。
appsettings.json ファイルの準備
appsettings.json ファイルと appsettings.Development.json ファイルを準備します。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"AppConfiguration": {
"Key": "(リリース用) appsettings.json アプリケーションの設定値です。"
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AppConfiguration": {
"Key": "(デバッグ用)appsettings.Development.json アプリケーションの設定値です。"
}
}
appsettings.json, appsettings.Development.json ファイルの[出力ディレクトリにコピー]プロパティを変更して、ファイルを出力ディレクトリにコピーする設定にします。
コード
下記のASP.NET アプリケーションのコードを記述します。
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 AppSettingsChangeAspNetCore
{
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")["Key"];
await context.Response.WriteAsync("Hello World!\r\n");
await context.Response.WriteAsync("Key:" + value1 + "\r\n");
});
});
}
}
}
解説
ロジックの詳細は
こちらの記事を参照してください。
DIにより、IConfiguration オブジェクトを取得し、メンバ変数に保持します。
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
アプリケーションルートのURLにアクセスすると、appsettings.json の値をレスポンスとして返す処理を実装します。
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
context.Response.ContentType = "text/plain; charset=utf-8;";
string value1 = _configuration.GetSection("AppConfiguration")["Key"];
await context.Response.WriteAsync("Hello World!\r\n");
await context.Response.WriteAsync("Key:" + value1 + "\r\n");
});
});
プロジェクトのプロパティの確認
プロジェクトのプロパティ画面を表示します。左側のメニューの[デバッグ]の項目をクリックします。下図の画面が表示されます。
[環境変数]の欄に "ASPNETCORE_ENVIRONMENT" の名前の変数が設定されており、値が "Development" になっていることを確認します。
起動プロファイルの追加 (launchSettings.json の修正)
起動のプロファイルを追加するために、launchSettings.json ファイルを修正します。
下記のコードに変更します。"IIS Express Release" のプロファイル項目を追加しています。 "ASPNETCORE_ENVIRONMENT": "Production" を設定しています。
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:33561",
"sslPort": 44349
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express Release": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
},
"AppSettingsChangeAspNetCore": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
なお、変更前の launchSettings.json は以下のコードです。
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:33561",
"sslPort": 44349
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"AppSettingsChangeAspNetCore": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
実行結果
launchSettings.json を修正後、Visual Studioの上部のデバッグ開始ボタンのドロップダウンボタンをクリックします。
下図のドロップダウンメニューが表示されます。メニューの中に、先に launchSettings.json に追加した "IIS Express Release" の項目が追加されていることが確認できます。
デバッグ開始ボタンのドロップダウンメニューの"IIS Express"をクリックして選択した状態が下図になります。
デバッグ開始ボタンの緑色の再生アイコンの右側の文字列が "IIS Express" の表示になります。
プロジェクトを実行します。WebブラウザでアプリケーションルートのURLにアクセスします。下図の画面が表示されます。
「(デバッグ用)appsettings.Development.json アプリケーションの設定値です。」の文字列が表示され、appsettings.Developmenmt.json の値が読み込まれていることが
確認できます。
続いて、デバッグ開始ボタンのドロップダウンメニューの"IIS Express Release"をクリックして選択した状態が下図になります。
デバッグ開始ボタンの緑色の再生アイコンの右側の文字列が "IIS Express Release" の表示になります。
プロジェクトを実行します。WebブラウザでアプリケーションルートのURLにアクセスします。下図の画面が表示されます。
「(リリース用) appsettings.json アプリケーションの設定値です。」の文字列が表示され、appsettings.json ファイルの値が読み込まれていることが、
確認できます。
実行プロファイルを変えることで、appsettings.json ファイルを切り替える設定ができました。
プロプロセッサ ディレクティブで切り替える方法
プリプロセッサ ディレクティブ (#if #else #endif) を利用して appsettings.json ファイルを切り替える方法です。
appsetting.json ファイルの準備
appsettings.json ファイルを準備します。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"AppConfiguration": {
"Key": "(リリース用)アプリケーションの設定値です。"
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"AppConfiguration": {
"Key": "(デバッグ用)アプリケーションの設定値です。"
}
}
コード
下記のコードを記述します。
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 AppSettingsChangeAspNetCorePreProcessor
{
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")["Key"];
await context.Response.WriteAsync("Hello World!\r\n");
await context.Response.WriteAsync("Key:" + value1 + "\r\n");
});
});
}
}
}
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AppSettingsChangeAspNetCorePreProcessor
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
#if DEBUG
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) => {
config.Sources.Clear();
config.AddJsonFile("appsettings_debug.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
if (args != null) {
config.AddCommandLine(args);
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
#else
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
#endif
}
}
解説
Startup.cs
Startup,cs ファイルは先の例と同じコードを利用しています。
ロジックの詳細は
こちらの記事を参照してください。
Program.cs
プリプロセッサ ディレクティブ を利用してビルド設定によりコンパイルするコードを変えています。
#if DEBUG
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) => {
config.Sources.Clear();
config.AddJsonFile("appsettings_debug.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
if (args != null) {
config.AddCommandLine(args);
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
#else
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
#endif
ソリューション構成のモードモードが Debug でない場合、すなわち、Release の場合は #else #endif ブロックの下記コードがコンパイルされます。
このコードはASP.NET アプリケーション作成時に Program.cs ファイルに生成されるコードと同じであり、デフォルトのConfigure設定を作成する
コードになります。
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
ソリューション構成のモードが"Debug"の場合は、下記コードがコンパイルされます。
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) => {
config.Sources.Clear();
config.AddJsonFile("appsettings_debug.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
if (args != null) {
config.AddCommandLine(args);
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
以下のコードがASP.NET アプリケーションの設定を作成するコードです。
デフォルトの設定と異なる設定をするため、最初に
config.Sources.Clear();
メソッドを呼び出し、デフォルトのルール設定をクリアします。
続いて、
config.AddJsonFile()
メソッドを呼び出し設定ファイルを設定しますが、アプリケーションの構成が"Debug"の場合は、デフォルトの appsettings.json ファイルではなく、
appsettings_debug.json ファイルを参照する動作に変更しています。
.ConfigureAppConfiguration((hostingContext, config) => {
config.Sources.Clear();
config.AddJsonFile("appsettings_debug.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
if (args != null) {
config.AddCommandLine(args);
}
})
実行結果
上記のプロジェクトをソリューション構成を"Debug"で実行します。下図の画面が表示されます。
「(デバッグ用)アプリケーションの設定値です。」のメッセージが表示され、"appsettings_debug.json" ファイルの値が読み出されていることが確認できます。
ソリューション構成を "Release" に変更してプロジェクトを実行します。下図の画面が表示されます。
「(リリース用)アプリケーションの設定値です。」のメッセージが表示され、"appsettings.json" ファイルの値が読み出されていることが確認できます。
プロプロセッサ ディレクティブを利用して、ソリューション構成が "Debug" の場合と "Release" の場合で、appsettings.json ファイルを切り替えることができました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2022-11-07
作成日: 2021-07-19