代碼改變世界

.Net Core3.0 配置Configuration

2019-10-26 11:44  成天  閱讀(...)  評論(... 編輯 收藏

準備

.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").Value+ "\r\n\n";
          
            var logSection = _config.GetSection("Logging:LogLevel");
            var configurationSections = logSection.GetChildren();
            foreach (var sections in configurationSections) 
            {
                jsonValue += $"{sections.Path}:{sections.Value}";
                jsonValue += "\r\n";
            }
            jsonValue += "\r\n";
 

配置指定json文件綁定至類

新建一個json文件-AAAppSettings.json

{
  "AA": {
    "RabbitMqHostUrl": "rabbitmq://localhost:5672",
    "RabbitMqHostName": "localhost",
    "RabbitMqUserName": "admin",
    "RabbitMqPassword": "123"
  }
}

使用ConfigureAppConfiguration方法配置指定的json文件

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddJsonFile("AAAppSettings.json", optional: true, reloadOnChange: true);
            })

使用bind方法綁定到新建的類上如:   

 public partial class AAConfig
    {
        public string RabbitMqHostUrl { get; set; }
        public string RabbitMqHostName { get; set; }
        public string RabbitMqUserName { get; set; }
        public string RabbitMqPassword { get; set; }
    }
var aaConfig = new AAConfig();
_config.GetSection("AA").Bind(aaConfig);
jsonValue += aaConfig.RabbitMqHostUrl + "\r\n";
jsonValue += aaConfig.RabbitMqHostName + "\r\n";
jsonValue += aaConfig.RabbitMqUserName + "\r\n";
jsonValue += aaConfig.RabbitMqPassword + "\r\n";
return jsonValue;

運行輸出:

三d开奖结果走势图