ASP.NET Core 中的配置是使用一個或多個配置提供程序執行的。 配置提供程序使用各種配置源從鍵值對讀取配置數據:
-
設置文件,例如 appsettings.json
-
環境變量
-
Azure Key Vault
-
Azure 應用程序配置
-
命令行參數
-
已安裝或已創建的自定義提供程序
-
目錄文件
-
內存中的 .NET 對象
獲取配置的鍵值可以使用Configuration["MyKey"],有多層次的鍵值的話可以用冒號分隔Configuration["MyKey:MyKeyCh"],獲取的結果為字符串。
可以通過GetValue方法返回指定的數據類型,並設置默認值,如下代碼99為默認值。
Configuration.GetValue<int>("NumberKey", 99)
可以使用GetSection方法返回指定鍵的子配置數據。
var config = Configuration.GetSection("MyKey"); //config["Key1"]; //config["Key2"];
GetSection永遠不會返回null,如果鍵匹配不到,則會返回空IConfigurationSection,並且Value會為null。 我們可以用Exists方法來判斷是存在該節點。
config.Exists() ? "存在" : "不存在"
通過GetChildren方法可以獲取GetSection獲取的節點的所有鍵值對。
var selection = Config.GetSection("section2"); if (!selection.Exists()) { throw new System.Exception("section2 does not exist."); } var children = selection.GetChildren(); foreach (var subSection in children) { int i = 0; var key1 = subSection.Key + ":key" + i++.ToString(); var key2 = subSection.Key + ":key" + i.ToString(); s += key1 + " value: " + selection[key1] + "\n"; s += key2 + " value: " + selection[key2] + "\n"; }
配置的鍵值有以下的要求:
鍵:
1.不區分大小寫。 例如,conn和Conn被視為等效鍵。
2.如果在多個配置提供程序中設置了某一鍵和值,則會使用最后添加的提供程序中的值。
3.分層鍵
(1)在配置 API 中,冒號分隔符 (:) 適用於所有平台。
(2)在環境變量中,冒號分隔符可能無法適用於所有平台。 所有平台均支持采用雙下划線 __,並且它會自動轉換為冒號 :。
(3)在 Azure Key Vault 中,分層鍵使用 -- 作為分隔符。 當機密加載到應用的配置中時,Azure Key Vault 配置提供程序 會自動將 -- 替換為 :。
4.ConfigurationBinder 支持使用配置鍵中的數組索引將數組綁定到對象。
值:
1.為字符串。
2.NULL 值不能存儲在配置中或綁定到對象。
一、默認配置
.Net Core的默認配置由CreateDefaultBuilder按照以下的順序提供:
-
ChainedConfigurationProvider:添加現有 IConfiguration 作為源。 在默認配置示例中,添加主機配置,並將它設置為應用配置的第一個源。
-
使用JsonConfigurationProvider加載 appsettings.json 。
-
使用JsonConfigurationProvider加載 appsettings.Environment.json 。 例如,appsettings.Production.json 和 appsettings.Development.json 。
-
應用在 Development環境中運行時的應用機密。
-
使用環境變量配置提供程序通過環境變量提供。
-
使用命令行配置提供程序通過命令行參數提供。
后加載的配置會覆蓋掉前面加載的配置。例如 appsettings.json和appsettings.Development.json都設置了一個叫MyKey的鍵,那獲取到MyKey的值會是appsettings.Development.json配置的,如下:
appsettings.json的配置:
{
"MyKey": "Value" }
appsettings.Development.json的配置:
{
"MyKey": "developmentValue" }
在Startup.cs中運行:
app.Run(async context => { await context.Response.WriteAsync(Configuration["MyKey"]); });
得到結果:

二、使用選項模式綁定配置數據
選項模式是讀取配置數據的首選方式,也就是把配置數據綁定到類對象上,這個類有幾個要求:
1.必須是包含公共無參數構造函數的非抽象類。
2.類的屬性必須有get和set。
綁定的方法使用IConfiguration的Configuration.GetSection(鍵名).Bind(對象)或者Configuration.GetSection(鍵名).Get<類>()。
我們在appsettings.json中加入以下數據:
"MyKey": { "Name": "my name is tom", "Age": "my age is 12" }
然后建立一個選項類MyOptions:
public class MyOptions { public string Name { get; set; } public string Age { get; set; } }
在Starup.cs中如下代碼:
app.Run(async context => { MyOptions myOptions = new MyOptions(); Configuration.GetSection("MyKey").Bind(myOptions);
//Configuration.GetSection("MyKey").Get<MyOptions>(); await context.Response.WriteAsync(myOptions.Name + "," + myOptions.Age); });
運行可以看到輸出結果。輸出的結果會隨這appsettings.json的配置更改而更改哦。
當然,我們還可以通過將選項類注入到依賴注入服務容器中,來實現綁定,如下。
services.Configure<MyOptions>(Configuration.GetSection("MyKey"));
但是,這種方式不會讀取在應用啟動后對 JSON 配置文件所做的更改。不過可以通過配置reloadOnChange: true來啟用對應配置文件來實現,如下。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); }) .UseStartup<Startup>();
三、配置環境變量
在window中環境變量在系統屬性->環境變量中:

如圖可以看到有一個環境變量叫NUMBER_OF_PROCESSORS、一個叫DriverData,我們可以直接獲取DriverData,或通過AddEnvironmentVariables方法指定環境變量的前綴,在獲取環境變量的值的時候會自動忽略前綴,如下。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables("NUMBER_"); config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); }) .UseStartup<Startup>();
app.Run(async context => { await context.Response.WriteAsync(Configuration["OF_PROCESSORS"]+","+Configuration["DriverData"]); });
運行可以得到結果:

在 launchSettings.json 中設置的環境變量將替代在系統環境中設置的變量。
四、加載配置文件
除了上面的加載方式和文件,我們還能加載自己創建的各類配置文件,可以是xml、json、ini,甚至是文件名。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { //加載ini config.AddIniFile("MyIniConfig.ini", optional: true, reloadOnChange: true); //加載json config.AddIniFile("MyJsonConfig.json", optional: true, reloadOnChange: true); //加載xml config.AddIniFile("MyXmlConfig.xml", optional: true, reloadOnChange: true); //文件名 var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files"); config.AddKeyPerFile(directoryPath: path, optional: true); //內存 var Dict = new Dictionary<string, string> { {"MyKey", "Dictionary MyKey Value"}, {"Position:Title", "Dictionary_Title"}, {"Position:Name", "Dictionary_Name" }, {"Logging:LogLevel:Default", "Warning"} }; config.AddInMemoryCollection(Dict); }) .UseStartup<Startup>();
文件名以_下划線分隔,Key_Name相當於Key:Name。文件的directoryPath參數必須是絕對路徑,第二個參數是目錄的路徑。
