一. ASP.NET Core 中的配置概述
ASP.NET Core 中的應用配置是基於鍵值對,由configuration 程序提供。 configuration 將從各種配置源提供程序操作鍵值對,這些配置源可以是:
(1) Azure Key Vault(是基於雲的服務的安全存儲應用機密)
(2) 命令行參數
(3)(已安裝或已創建的)自定義提供程序(自定義實現IConfigurationSource)
(4) 目錄文件(Key-per-file)
(5) 環境變量(EnvironmentVariables)
(6) 內存中的 .NET 對象
(7) 設置文件(從文件系統加載配置)
configuration 程序提供配置依賴於以下內容,本章后面都會介紹具體使用:
(1) 使用 SetBasePath 設置應用程序的基本路徑。 通過引用 Microsoft.Extensions.Configuration.FileExtensions 包,可以向應用提供 SetBasePath。
(2) 使用 GetSection 解析配置文件的各個部分。 通過引用 Microsoft.Extensions.Configuration 包向應用提供 GetSection。
(3) 使用 Bind 和 Get<T> 將配置綁定到 .NET 類。 通過引用 Microsoft.Extensions.Configuration.Binder 包向應用提供 Bind 和 Get<T>。 ASP.NET Core 1.1 或更高版本中提供了 Get<T>。
1.1 文件分層結構數據
通過configuration api 能夠通過在配置鍵中使用分隔符來保持分層配置數據。說明白點就是約定的數據結構。通過configuration api的GetSection 和 GetChildren 方法可用於讀取配置數據中某節點的值,下面簡單先演示下效果。示例在 appsettings.json文件中添加section 節點的結構化鍵值對。如下所示:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "mykey": "d", "section0": { "key0": "value", "key1": "value" }, "section1": { "key0": "value", "key1": "value" } }
public class Page1Model : PageModel { //using Microsoft.Extensions.Configuration; public Page1Model(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void OnGet() { string val = Configuration.GetSection("section0").GetSection("key0").Value; //val 值為: value } }
在OtherPages/page1中讀取上面文件中的節點。上面通過服務的實現的IConfiguration並沒有在程序中顯示讀取appsettings.json文件,那為什么能讀出到該文件的鍵值對呢? 本章帶着這個問題在繼續了解。
1.2 配置約定
應用的依賴關系注入 (DI) 容器中提供了 IConfiguration。在程序應用啟動時,IConfiguration將按照指定的配置文件順序讀取配置源。
1) 配置來源中的鍵有以下約定:
(1) 鍵不區分大小寫。比如能過GetSection讀取時,可以不管大小寫。
(2) 配置來源中設置相同鍵的值,則取配置來源中鍵上設置的最后一個值。比如appsettings.json與appsettings.{Environment}.json多個配置來源文件。
(3) 分層鍵。如在json文件中多個節點,冒號分隔符 (:
) 適用於所有平台。而在環境變量的來源配置中,所有平台均支持采用雙下划線 (__)。
(4) ConfigurationBinder 支持使用配置鍵中的數組索引將數組綁定到類對象。
2) 配置值采用以下約定:
(1) 值是字符串。
(2) NULL 值不能存儲在配置中或綁定到對象。
1.3 配置來源提供程序的順序
對於上面的7種配置來源提供程序,IConfiguration操作的順序是按照啟動時指定的配置順序操作配置源。在ConfigureAppConfiguration代碼中設置的配置源提供程序,應以特定順序排列以符合基礎配置源的優先級。典型順序為:
(1) 文件(appsettings.json、appsettings.{Environment}.json,其中 {Environment} 是應用的當前托管環境)。
(2) Azure 密鑰保管庫。
(3) 用戶機密 (Secret Manager)(僅限開發環境中)。
(4) 環境變量。
(5) 命令行參數。
通常的做法是將命令行配置提供程序置於一系列提供程序的末尾,以允許命令行參數替代由其他提供程序設置的配置。在使用 CreateDefaultBuilder 初始化新的 WebHostBuilder 時,將使用此提供程序序列。
上面講到為什么會自動讀取appsettings.json文件瞞下的伏筆。在這里有了答案。Configuration提供程序默認會讀取appsettings.json、appsettings.{Environment}.json。
1.4 ConfigureAppConfiguration 添加配置提供程序
構建 Web 主機時調用 ConfigureAppConfiguration 以指定應用的配置提供程序以及 CreateDefaultBuilder 自動添加的配置提供程序:
public static Dictionary<string, string> arrayDict = new Dictionary<string, string> { {"array:entries:0", "value0"}, {"array:entries:1", "value1"}, {"array:entries:2", "value2"}, {"array:entries:4", "value4"}, {"array:entries:5", "value5"} }; /// <summary> /// Configuration Providers示例 /// </summary> /// <param name="args"></param> /// <returns></returns> public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { //顯示設置當前程序運行目錄 config.SetBasePath(Directory.GetCurrentDirectory()); //設置內存中的 .NET 對象 config.AddInMemoryCollection(arrayDict); //設置文件, optional選擇項為false時 必需存在該文件 config.AddJsonFile("json_array.json", optional: false, reloadOnChange: false); config.AddJsonFile("starship.json", optional: true, reloadOnChange: false); config.AddXmlFile("tvshow.xml", optional: true, reloadOnChange: false); //EF以后在講 自定義提供程序 // config.AddEFConfiguration(options => options.UseInMemoryDatabase("InMemoryDb")); //最后設置命令行參數 config.AddCommandLine(args); }) .UseStartup<Startup>();
二. 命令行配置提供程序 AddCommandLine
CommandLineConfigurationProvider 在運行時從命令行參數鍵值對加載配置,要激活命令行配置,請在 ConfigurationBuilder 的實例上調用 AddCommandLine 擴展方法。 如果需要使用命令行參數覆蓋其它配置,請在 ConfigureAppConfiguration 中調用應用的其他提供程序並最后調用 AddCommandLine。
下面示例,使用控制台作為啟動程序。打開cmd 輸入dotnet命令,在后面輸入命令行配置參數CommandLineKey1=value1, 在瀏覽器page2中顯示該命令行配置value值。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { // Call other providers here and call AddCommandLine last. config.AddCommandLine(args); }) .UseStartup<Startup>();
-- page2頁面獲取命令行 @using Microsoft.Extensions.Configuration; @inject IConfiguration Configuration; <p>Configuration CommandLine value for 'key':@Configuration["CommandLineKey1"] </p>
2.1 命令行配置自變量示例
dotnet run CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 dotnet run --CommandLineKey1 value1 /CommandLineKey2 value2 dotnet run CommandLineKey1= CommandLineKey2=value2
2.2 交換映射
交換映射字典鍵規則:(1)交換必須以單划線 (-) 或雙划線 (--) 開頭 。(2) 交換映射字典不得包含重復鍵。下面是一個示例:
public static readonly Dictionary<string, string> _switchMappings = new Dictionary<string, string> { { "-CLKey1", "CommandLineKey1" }, { "-CLKey2", "CommandLineKey2" } };
config.AddCommandLine(args, _switchMappings);
創建交換映射字典后,它將包含下表所示的數據。
鍵 | 值 |
-CLKey1 | CommandLineKey1 |
-CLKey2 | CommandLineKey2 |
三. 環境變量配置提供程序 AddEnvironmentVariables
EnvironmentVariablesConfigurationProvider 在運行時從環境變量鍵值對加載配置。要激活環境變量配置,請在 ConfigurationBuilder 的實例上調用 AddEnvironmentVariables 擴展方法。
環境變量配置提供程序是在用戶機密 (Secret Manager)和 appsettings.json 文件建立后調用。 調用AddEnvironmentVariables方法具有重載, 如果調用沒有給前綴參數,則具有表中所示前綴的環境變量將加載到應用中。 如果有向 AddEnvironmentVariables
提供前綴,將篩選加載到應用的配置中的環境變量。
下面示例為 AddEnvironmentVariables
方法提供前綴,添加要篩選前綴 ASPNETCORE_上的環境變量。將篩選加載到應用的配置中的環境變量。
//添加具有指定前綴的環境變量的配置值。 config.AddEnvironmentVariables(prefix: "ASPNETCORE_");
下面顯示的是ASPNETCORE_為前綴的主機的配置信息。主機配置格式 ASPNETCORE_{configurationKey} 的環境變量。 例如 ASPNETCORE_ENVIRONMENT。關於ASPNETCORE_前綴的環境信息可參考“主機配置值”。下面是Configuration從查看ASPNETCORE_為前綴的主機的配置信息。
參考文獻
官方資料:asp.net core 配置