雜物儲存室 Coding Blog

在 Console 取得 appsetings.json

安裝套件

這邊使用版本 3.1.2

dotnet add package Microsoft.Extensions.Configuration.Json --version 3.1.2

.cs

var config = new ConfigurationBuilder()
    .AddJsonFile("appSettings.json", optional: true)
    .AddJsonFile($"appSettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
    .Build();

取得 connect string

var connectionString = config.GetConnectionString("DefaultConnection");

取得 value

var logPath = config.GetSection("LogPath").Value;

使用 Model 包裝

var mailSetting = config.GetSection("MailSettings").Get<MailSettingModel>();
tags: [ DotNetCore ]