1. 程式人生 > 程式設計 >.Net Core3.0 配置Configuration的實現

.Net Core3.0 配置Configuration的實現

準備

.NET core和.NET專案配置上有了很大的改變,支援的也更加豐富了比如命令列,環境變數,記憶體中.NET物件,設定檔案等等。.NET專案我們常常把配置資訊放到webConfig 或者appConfig中。配置相關的原始碼https://github.com/aspnet/Extensions;如果開啟原始碼專案如果遇到以下錯誤,未遇到直接跳過。

.Net Core3.0 配置Configuration的實現

錯誤提示: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中制定的版本是否一致:然後修改即可

.Net Core3.0 配置Configuration的實現

開始

新建個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",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檔案:

.Net Core3.0 配置Configuration的實現

將檔案讀入配置時,會建立一下唯一的分層健來儲存配置值:

  • 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";

.Net Core3.0 配置Configuration的實現

配置指定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",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;

執行輸出:

.Net Core3.0 配置Configuration的實現

到此這篇關於.Net Core3.0 配置Configuration的實現的文章就介紹到這了,更多相關.Net Core3.0 配置Configuration內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!