ASP.NET Coreでappsettings.jsonを使いこなす
本章では、ASP.NET Coreで、プロジェクト特有の固有値(外部ライブラリのライセンスキー等)を外部ファイルで利用する方法について共有します。
はじめに
ASP.NET MVCでは、Web.configファイルの「appSettings」セクションで、keyとvalueを記述して利用していました。ASP.NET Coreでは、appsettings.jsonファイルに、Web.configと同様に、keyとvalueの組合せを記述して利用します。
記載ルール
appsettings.jsonでは、以下サイトのように、JSON形式で記述します。
JSON Introduction
ASP.NET MVCでは、「configuration」セクションの下に「appSettings」セクションを用意して、その中にkey valueを記述していました。ASP.NET Coreでは、直接appSettingsセクションを記述します。また名前は自由です。本章では「AppSettings」として説明します。
ソースコード
まず、「AppSettings」をサービスとして利用できるよう、モデルクラスを用意します。
【AppSettingsConfig.cs】
public class AppSettingsConfig { public int Hoge { get; set; } public string HogeHoge { get; set; } }
次に設定ファイルが読み込めるよう、サービスとしてjsonファイル読み込みの設定を行います。
【Startup.cs】
public class Startup { public static IConfigurationRoot Configuration { get; private set; } public Startup(IHostingEnvironment env) { // appsettings.jsonファイルの読み込み var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // appsettings.jsonで設定したKeyValueをエンティティにバインド services.Configure<AppSettingsConfig>(Configuration.GetSection("AppSettings")); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{param?}"); }); } }
最後に実際にコントローラーで利用してみましょう。
【Controllers/HomeController.cs】
public class HomeController : Controller { readonly IOptions<AppSettingsConfig> appSettings; public ActionLogFilter(IOptions<AppSettingsConfig> _appSettings) { appSettings = _appSettings; } public ActionResult Index() { ViewData["HogeHoge"] = appSettings.Value.HogeHoge return View(); } }
【Views/Home/Index.cshtml】
@ViewData["HogeHoge"]
実行すると、WEBページに「MS Project」が表示されます。