升級ASP.NET Core後,配置的讀取是第一個要明確的技術。原先的App.Config、Web.Config、自定義Config在ASP.NET Core中如何正常使用。有必要好好總結整理一下,相信你們都會用到。html
首先,看一下ASP.NET Core中的配置提供程序(Configuration Providers):web
1、配置提供程序(Configuration Providers)json
ASP.NET Core 使用一個或多個配置提供程序來讀取配置:windows
咱們經過下面的代碼,輸出配置提供程序的加載順序:app
var configRoot = (IConfigurationRoot)Configuration; foreach (var provider in configRoot.Providers.ToList()) { Debug.WriteLine(provider.ToString() + "\n"); }
輸出有5個: ide
接下來咱們咱們重點介紹「應用程序配置文件」,「環境變量」,「命令行參數」,「app.config」 這四種最經常使用的配置讀取方式,經過代碼的方式,示例給你們:ui
2、讀取應用程序設置文件appsettings.jsonspa
咱們使用ASP.NET Core工程中默認的appsettings.json文件命令行
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
經過代碼讀取配置code
var allowedHosts = Configuration["AllowedHosts"]; var defaultLogLevel = Configuration["Logging:LogLevel:Default"]; Debug.WriteLine("allowedHosts:" + allowedHosts + "\n"); Debug.WriteLine("defaultLogLevel:"+defaultLogLevel + "\n");
實際輸出:
allowedHosts:*
defaultLogLevel:Information
若是想讀取整個的LogLevel對象,如何實現?
新建LogLevel類和Logging類
[DataContract] public class LogLevel { [DataMember(Name = "Default")] public string Default { get; set; } [DataMember(Name = "Microsoft")] public string Microsoft { get; set; } [DataMember(Name ="Microsoft.Hosting.Lifetime")] public string MicrosoftHostingLifetime { get; set; } } [DataContract] public class Logging { [DataMember] public LogLevel LogLevel { get; set; } }
讀取Logging配置示例代碼:
Logging logConfig = new Logging(); Configuration.GetSection("Logging").Bind(logConfig);
var lifetime = Configuration["Logging:LogLevel:Microsoft.Hosting.Lifetime"];
logConfig.LogLevel.MicrosoftHostingLifetime = lifetime;
上述代碼中,對Lifetime屬性的設置,經過如下方式實現,Bind的方式由於key匹配的問題,沒法完成匹配。
Configuration["Logging:LogLevel:Microsoft.Hosting.Lifetime"];
這個地方補充一個帶環境類型的應用設置文件的價值順序:好比說按環境分appsettings.json文件
默認的JsonConfigurationProvider ,按如下順序加載 appsettings.json文件:
① appsettings.json
② appsettings.Environment.json,例如appsettings.Development.json ,appsettings.Production.json
關於appsettings.Environment.json,Environment的設置主頁在Program時指定的變量:
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseEnvironment("Development"); webBuilder.UseStartup<Startup>(); }); }
3、環境變量讀取
按照配置的加載順序,EnvironmentVariablesConfigurationProvider從環境變量中讀取配置信息,在appsettings.json和Secret manager讀取配置以後。
這個地方有個分隔符的注意點,由於 :並非在全部平臺上都支持,建議統一使用__(雙下劃線),運行時會將__統一替換爲:
先經過如下命令,設置環境變量:
set Key1="Value1" set Logging__LogLevel__Customer=Information
代碼中讀取環境變量的配置
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostBuilder, config) => { config.AddEnvironmentVariables(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseEnvironment("Development"); webBuilder.UseStartup<Startup>(); });
修改Startup中Configure方法:讀取配置並輸出
var key1Value = Configuration["Key1"]; var logLevel = Configuration["Logging:LogLevel:Customer"]; Console.WriteLine("key1Value:" + key1Value + "\n"); Console.WriteLine("logLevel:" + logLevel + "\n");
4、命令行參數讀取
命令行配置提供程序CommandLineConfigurationProvider,將在如下配置源以後從命令行參數鍵值對加載配置:
繼續使用第三章中的示例工程,新建CMD命令行,輸入如下dotnet run指令:
dotnet run Key1="Value1" Logging:LogLevel:Customer="Information"
5、app.config讀取
這個場景最大的做用就是兼容原有ASP.NET Web.Config文件!
首先添加Nuget引用:System.Configuration.ConfigurationManager
新增app.config文件:
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="ConfigKey1" value="Value" /> </appSettings> </configuration>
使用原有ConfigurationManager讀取配置:
var value = System.Configuration.ConfigurationManager.AppSettings["ConfigKey1"]; Console.WriteLine("ConfigKey1:" + value + "\n");
以上就是ASP.NET Core經常使用的「應用程序配置文件」,「環境變量」,「命令行參數」,「app.config」 配置讀取方式,分享給你們。
周國慶
2020/4/1