准备

.NET core和.NET项目配置上有了很大的改变,支持的也更加丰富了比如命令行,环境变量,内存中.NET对象,设置文件等等。.NET项目我们常常把配置信息放到webConfig 或者appConfig中。配置相关的源码https://github.com/aspnet/Extensions;如果打开源码项目 如果遇到以下错误,未遇到直接跳过。

错误提示: error : The project file cannot be opened by the project system, because it is missing some critical imports or the referenced SDK cannot be found. Detailed Information:

解决办法:查看本地安装的sdk 与 global.json中制定的版本是否一致:然后修改即可

开始

新建个Asp.net Core web应用程序系统默认创建了appsettings.json ;在应用启动生成主机时调用CreateDefaultBuilder方法,默认会加载appsettings.json。代码如下:

复制代码
public static IHostBuilder CreateDefaultBuilder(string[] args)         {             var builder = new HostBuilder(); ​             builder.UseContentRoot(Directory.GetCurrentDirectory());             builder.ConfigureHostConfiguration(config =>             {                 config.AddEnvironmentVariables(prefix: "DOTNET_");                 if (args != null)                 {                     config.AddCommandLine(args);                 }             }); ​             builder.ConfigureAppConfiguration((hostingContext, config) =>             {                 var env = hostingContext.HostingEnvironment; ​                 config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)                       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); ​                 if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))                 {                     var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));                     if (appAssembly != null)                     {                         config.AddUserSecrets(appAssembly, optional: true);                     }                 }
复制代码
利用 GetValue,GetSection,GetChildren读取appsettings.json 键值对 。我们打开appsettings.json文件:

将文件读入配置时,会创建一下唯一的分层健来保存配置值:

  • Logging:LogLevel:Default

  • Logging:LogLevel:System

  • Logging:LogLevel:Microsoft

  • Logging:LogLevel:Microsoft.Hosting.Lifetime

  • AllowedHosts

复制代码
 var jsonValue = $"AllowedHosts:{_config["AllowedHosts"]}"+ "\r\n";             jsonValue += "Logging:LogLevel:Default:" + _config.GetValue<string>("Logging:LogLevel:Default")+ "\r\n"; ​             //GetSection 返回IConfigurationSection;如果未匹配到 返回null             //jsonValue += "---" + _config.GetSection("Logging:LogLevel:System");            jsonValue += "Logging:LogLevel:System:" + _config.GetSection("Logging:LogLevel:System