翻譯 – ASP.NET Core 基本知識 – 配置(Configuration)

翻譯自 //docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0

ASP.NET Core 中的配置使用一個或者多個配置提供程(configuration providers)序實現。配置提供程式從多種鍵值對中的配置源中讀取配置數據:

  • 設置文件,例如 appsetting.json
  • 環境變數
  • Azure 鍵庫
  • Azure App 配置
  • 命令行參數
  • 自定義提供器,安裝的或者創建的
  • 目錄文件
  • 記憶體中的 .NET 對象

本話題提供 ASP.NET Core 中關於配置的資訊。更多關於在控制台應用程式中使用配置的資訊,查看 .NET Configuration.

默認配置

使用 dotnet new 或者 Visual Studio 創建的 ASP.NET Core web 應用程式生成以下程式碼:

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.UseStartup<Startup>();
            });
}

CreateDefaultBuilder 按照以下順序為應用程式提供默認配置:

  1. ChainedConfigurationProvider:添加一個現存的 IConfiguration 作為一個源。在一個默認配置例子中,添加主機(host)配置並且設置它作為第一個應用程式配置的源。
  2. appsettings.json 使用 JSON 配置提供器(JSON configuration provider)。
  3. appsetttings.Environment.json 使用 JSON 配置提供器(JSON configuration provider)。例如,appsettings.Production.json 和 appsettings.Developments.json。
  4. App secrets,當應用程式運行在開發 (Development) 環境中。
  5. 環境變數使用  Environment Variables configuration provider
  6. 命令行參數使用 Command-line configuration provider

後添加的配置提供器會覆蓋先前添加的鍵值設置。例如,如果 MyKey 同事在 appsettings.json 和 環境變數中設置,環境變數的值將會被使用。如果使用默認的配置提供器,命令行配置提供器(Command-line configuration provider) 將會覆蓋所有的提供器。

關於 CreateDefaultBuilder 的更多資訊,查看 Default builder settings

下面的程式碼展示了使能的配置提供器的添加順序:

public class Index2Model : PageModel
{
    private IConfigurationRoot ConfigRoot;

    public Index2Model(IConfiguration configRoot)
    {
        ConfigRoot = (IConfigurationRoot)configRoot;
    }

    public ContentResult OnGet()
    {           
        string str = "";
        foreach (var provider in ConfigRoot.Providers.ToList())
        {
            str += provider.ToString() + "\n";
        }

        return Content(str);
    }
}

appsettings.json

考慮下面的 appsettings.json 文件:

{
  "Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  },
  "MyKey":  "My appsettings.json Value",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

示例 (sample download) 中的程式碼展示了幾個上面的配置設置:

public class TestModel : PageModel
{
    // requires using Microsoft.Extensions.Configuration;
    private readonly IConfiguration Configuration;

    public TestModel(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public ContentResult OnGet()
    {
        var myKeyValue = Configuration["MyKey"];
        var title = Configuration["Position:Title"];
        var name = Configuration["Position:Name"];
        var defaultLogLevel = Configuration["Logging:LogLevel:Default"];


        return Content($"MyKey value: {myKeyValue} \n" +
                       $"Title: {title} \n" +
                       $"Name: {name} \n" +
                       $"Default Log Level: {defaultLogLevel}");
    }
}

默認的 JsonConfigurationProvider 按照以下順序載入配置:

1. appsettings.json

2. appsettings.Environment.json:例如,appsettings.Production.json 和 appsettings.Development.json 文件。文件的環境版本基於 IHostingEnvironment.EnvironmentName,更多資訊,查看 Use multiple environments in ASP.NET Core.

appsettings.Environment.json 中的值會覆蓋 appsettings.json 中的值。例如,默認的:

  • 在開發環境中,appsettings.Development.json 配置會覆蓋 appsettings.json 中存在的值
  • 在生產環境中,appsettings.Production.json 的配置會覆蓋 appsettings.json 中存在的值,例如,當部署應用程式到 Azure 上的時候。

使用選項模型綁定繼承配置數據

讀取相關配置值的推薦方式是使用選項模型 (options pattern)。例如,讀取下面的配置值:

"Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  }

創建 PositionOptions 類:

public class PositionOptions
{
    public const string Position = "Position";

    public string Title { get; set; }
    public string Name { get; set; }
}

一個選項類:

  • 必須是帶有公共無參數的構造方法的非抽象類
  • 所有公共的可讀寫的屬性類型要被綁定
  • 欄位沒有綁定。在前面的程式碼中,Position 沒有綁定。使用 Position 屬性,因此字元串 “Position” 就不用在綁定類到一個配置提供器的時候硬編碼在應用程式中

下面的程式碼:

public class Test22Model : PageModel
{
    private readonly IConfiguration Configuration;

    public Test22Model(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public ContentResult OnGet()
    {
        var positionOptions = new PositionOptions();
        Configuration.GetSection(PositionOptions.Position).Bind(positionOptions);

        return Content($"Title: {positionOptions.Title} \n" +
                       $"Name: {positionOptions.Name}");
    }
}

在上面的程式碼中,默認的,在應用程式啟動後對於 JSON 配置文件的改變也會被讀取到。

ConfigurationBinder.Get<T> 綁定和返回指定的類型。ConfigurationBinder.Get<T> 可能比使用 ConfigurationBinder.Bind 更方便。下面的程式碼展示了如何使用 ConfigurationBinder.Get<T> 使用 PositionOptions 類:

public class Test21Model : PageModel
{
    private readonly IConfiguration Configuration;
    public PositionOptions positionOptions { get; private set; }

    public Test21Model(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public ContentResult OnGet()
    {            
        positionOptions = Configuration.GetSection(PositionOptions.Position)
                                                     .Get<PositionOptions>();

        return Content($"Title: {positionOptions.Title} \n" +
                       $"Name: {positionOptions.Name}");
    }
}

默認的,上面的程式碼會讀取到在應用程式啟動後對於 JSON 配置文件的更改。

使用 options patter 的一種方法是綁定 Position 區域並且添加到依賴注入服務容器 (dependency injection service container) 中。下面的程式碼中,PositionOptions 在 Configure 中被添加到服務容器中,並綁定到配置:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<PositionOptions>(Configuration.GetSection(
                                        PositionOptions.Position));
    services.AddRazorPages();
}

使用了上面的程式碼,下面的程式碼讀取 position options:

public class Test2Model : PageModel
{
    private readonly PositionOptions _options;

    public Test2Model(IOptions<PositionOptions> options)
    {
        _options = options.Value;
    }

    public ContentResult OnGet()
    {
        return Content($"Title: {_options.Title} \n" +
                       $"Name: {_options.Name}");
    }
}

上面的程式碼在應用程式啟動後不會讀取到對 JSON 配置文件的更改。如果要讀取應用程式啟動後的更改,可以使用 IOptionsSnapshot

使用默認(default)的配置,appsettings.json 和 appsettings.Environment.json 文件使能了  reloadOnChange: true 。在應用程式啟動後對 appsettings.json 和 appsettings.Environment.json 的更改會被 JSON configuration provider 讀取到。

查看本文檔中 JSON configuration provider 關於添加更多 JSON 配置文件的資訊。

合併服務集合

考慮下面的 ConfigureServices 方法,其中註冊服務和配置選項:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<PositionOptions>(
        Configuration.GetSection(PositionOptions.Position));
    services.Configure<ColorOptions>(
        Configuration.GetSection(ColorOptions.Color));

    services.AddScoped<IMyDependency, MyDependency>();
    services.AddScoped<IMyDependency2, MyDependency2>();

    services.AddRazorPages();
}

相關的一組的註冊可以被移動到擴展方法中去註冊服務。例如,配置服務被添加到下面的類中:

using ConfigSample.Options;
using Microsoft.Extensions.Configuration;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class MyConfigServiceCollectionExtensions
    {
        public static IServiceCollection AddConfig(
             this IServiceCollection services, IConfiguration config)
        {
            services.Configure<PositionOptions>(
                config.GetSection(PositionOptions.Position));
            services.Configure<ColorOptions>(
                config.GetSection(ColorOptions.Color));

            return services;
        }
    }
}

其餘的服務在一個相似的類中被註冊。下面的 ConfigureServices 方法使用的新的擴展方法註冊服務:

public void ConfigureServices(IServiceCollection services)
{
    services.AddConfig(Configuration)
            .AddMyDependencyGroup();

    services.AddRazorPages();
}

備註:每一個 services.Add{GROUP_NAME} 擴展方法添加和潛在的會配置服務。例如,AddControllersWithViews 添加帶有視圖的 MVC 控制器的服務,AddRazorPages 添加帶有 Razor Pages 的服務。我們推薦應用程式遵守命名的約定。把擴展方法統一放到命名空間 Microsoft.Extensions.DependencyInjection 中去封裝一組服務的註冊。

安全和用戶秘密

數據配置指導:

  • 永遠不要把密碼或者其他敏感數據使用配置提供器保存在程式碼中或者保存在文本配置文件中。在開發過程中,可以使用 Secret Manager 工具保存秘密數據
  • 不要在開發環境或者測試環境中使用生產環境的秘密數據
  • 在工程外部指定秘密數據,以防被意外的提交到源程式碼倉庫中

默認的,用戶秘密配置源是在 JSON 配置源之後註冊的。因此,用戶秘密的鍵值會生效,而不是 appsettings.json 和 appsettings.Environment.json 中的鍵值。

更多關於存儲密碼或者其他敏感數據的資訊:

Azure Key Vault 為 ASP.NET Core 應用程式安全的存儲應用程式的秘密。更多資訊查看 Azure Key Vault Configuration Provider in ASP.NET Core

環境變數

使用默認的配置,EnvironmentVariablesConfigurationProvider 在讀取 appsettings.json,appsettings.Environment.json,和 user secrets 之後從環境變數載入鍵值對。因此,從環境變數讀取到的鍵值會覆蓋從 appsettings.json, appsettings.Environment.json 和 user secrets 中讀取到的值。

: 分隔符在所有平台上對於環境便令分級鍵都是不工作的。__ 雙下換線:

  • 所有平台都支援。例如, Bash 不支援 : 分隔符,但是支援 __
  • 會自動的被一個 : 替換

下面的設置命令:

  • 在 Windows 上設置前面示例(preceding exampl)中的環境鍵值和值
  • 使用示常式序(sample download)測試設置。dotnet run 命令必須在工程目錄中運行
set MyKey="My key from Environment"
set Position__Title=Environment_Editor
set Position__Name=Environment_Rick
dotnet run

上面的環境變數設置:

  • 僅僅在設置他們的命令行窗口中啟動的進程中
  • 不會被使用 Visual Studio 啟動的瀏覽器讀取

下面的  setx 命令可以被用來在 Windows 上設置環境鍵和值。不同於 set,setx 是持久化的。/M 在系統環境設置變數。如果沒有使用 /M 開關,一個用戶的環境變數會被設置。

setx MyKey "My key from setx Environment" /M
setx Position__Title Setx_Environment_Editor /M
setx Position__Name Environment_Rick /M

為了測試上面的命令會覆蓋 appsettings.json 和 asppsettings.Environment.json 的配置,需要做以下操作:

  • 使用 Visual Studio: 退出和重啟 Visual Studio
  • 使用命令行:啟動一個新的命令窗口,輸入 dotnet run

調用 AddEnvironmentVariables,使用一個字元串指定環境變數的前綴:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddEnvironmentVariables(prefix: "MyCustomPrefix_");
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

在上面的程式碼中:

當配置鍵值對被讀取的時候,前綴會被去除。

下面的命令測試自定義前綴:

set MyCustomPrefix_MyKey="My key with MyCustomPrefix_ Environment"
set MyCustomPrefix_Position__Title=Editor_with_customPrefix
set MyCustomPrefix_Position__Name=Environment_Rick_cp
dotnet run

默認配置 (default configuration) 載入帶有前綴為 DOTNET_ 和 ASPNETCORE_ 的環境變數和命令行參數。DOTNET_ 和 ASPNETCORE_ 前綴被 ASP.NET Core 用來配置主機和應用程式配置 (host and app configuration),不能用來作為用戶配置。更多關於主機和應用程式的配置,查看 .NET Generic Host

關於  Azure App Service,在設置 (Settings) > 配置 (Configuration) 頁面選擇 新建應用程式設置 (New application setting)。Azure 應用程式服務設置:

  • 在休息是加密,並通過加密通道傳輸
  • 暴露為環境變數

更多資訊,查看 Azure Apps: Override app configuration using the Azure Portal

查看 Connection string prefixes 了解關於 Azure 資料庫連接字元串的資訊。

 環境變數命名

環境變數的命名反映了 appsettings.json 文件的結構。層級中的每一個元素使用雙下劃線(推薦的)或者冒號分割開來。當一個元素的結構包含一個數組的時候,數組的索引應該被當做是當前路徑中的一個額外的元素名稱。考慮下面的 appsettings.json 文件和它在環境變數中等價的值。

appsettings.json

{
    "SmtpServer": "smtp.example.com",
    "Logging": [
        {
            "Name": "ToEmail",
            "Level": "Critical",
            "Args": {
                "FromAddress": "[email protected]",
                "ToAddress": "[email protected]"
            }
        },
        {
            "Name": "ToConsole",
            "Level": "Information"
        }
    ]
}

環境變數 (environment variables)

setx SmtpServer=smtp.example.com
setx Logging__0__Name=ToEmail
setx Logging__0__Level=Critical
setx Logging__0__Args__FromAddress=[email protected]
setx Logging__0__Args__ToAddress=[email protected]
setx Logging__1__Name=ToConsole
setx Logging__1__Level=Information

生成的 launchSettings.json 文件中環境變數的設置

在 launchSettings.json 中設置的環境變數會覆蓋那些在系統環境中設置的值。例如,ASP.NET Core web 模板會生成一個 lauchSettings.json 文件,文件中設置了

endpoint 配置:

"applicationUrl": "//localhost:5001;//localhost:5000"

對 applicationUrl 的配置設置環境變數 ASPNETCORE_URLS  並覆蓋環境中的值。

Escape environment variables on Linux

在 linux 上,URL 環境變數的值必須被 escape 後系統才能夠解析它。使用 linux systemd-escape 工具生成 http:–localhost:5001

groot@terminus:~$ systemd-escape http://localhost:5001
http:--localhost:5001

顯示環境變數

下面的程式碼在應用程式啟動的時候輸出顯示了環境變數和對應的值,在調試環境設置的時候非常有用:

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    var config = host.Services.GetRequiredService<IConfiguration>();

    foreach (var c in config.AsEnumerable())
    {
        Console.WriteLine(c.Key + " = " + c.Value);
    }
    host.Run();
}

命令行

使用默認的配置,CommandLineConfigurationProvider 在下列配置源之後從命令行參數鍵值對中載入配置:

  • appsettings.json 和 appsettings.Environment.json 文件
  • 開發環境中的 App secrets
  • 環境變數

默認的,在命令行中配置的值會覆蓋其它所有配置提供的值。

命令行參數

下面的命令使用 = 設置鍵和值:

dotnet run MyKey="My key from command line" Position:Title=Cmd Position:Name=Cmd_Rick

下面的命令使用 / 設置鍵值:

dotnet run /MyKey "Using /" /Position:Title=Cmd_ /Position:Name=Cmd_Rick

下面的命令使用 — 設置鍵值:

dotnet run --MyKey "Using --" --Position:Title=Cmd-- --Position:Name=Cmd--Rick

鍵值:

  • 必須緊跟 = ,或當值在一個空格後面的時候,鍵必須有個 — 或者 / 前綴
  • 當使用 = 的時候,值不是必須要有的,例如 MySetting=

在相同的命令行中,不要把使用 = 的鍵值對和使用空格的鍵值對的命令行參數混淆。

轉換映射

切換映射允許鍵名替換邏輯。可以給 AddCommandLine 方法提供一個切換替換的字典。

當切換映射字典被用到的時候,字典被用來檢查匹配命令行參數提供的鍵。日過命令行的鍵在字典中被找到,字典中的值就會被傳回用來設置應用程式配置的鍵值對。切換映射要求任何的命令行鍵使用一個單獨的破折號作為前綴。

切換映射字典鍵的規則:

  • 切換必須以 – 或者 — 開頭
  • 切換映射字典不能包含重複的鍵

 

使用一個切換映射字典,需要把它傳遞給 AddCommandLine 方法:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        var switchMappings = new Dictionary<string, string>()
         {
             { "-k1", "key1" },
             { "-k2", "key2" },
             { "--alt3", "key3" },
             { "--alt4", "key4" },
             { "--alt5", "key5" },
             { "--alt6", "key6" },
         };

        return Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddCommandLine(args, switchMappings);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    }
}

下面的程式碼展示了被替換的鍵的值:

public class Test3Model : PageModel
{
    private readonly IConfiguration Config;

    public Test3Model(IConfiguration configuration)
    {
        Config = configuration;
    }

    public ContentResult OnGet()
    {
        return Content(
                $"Key1: '{Config["Key1"]}'\n" +
                $"Key2: '{Config["Key2"]}'\n" +
                $"Key3: '{Config["Key3"]}'\n" +
                $"Key4: '{Config["Key4"]}'\n" +
                $"Key5: '{Config["Key5"]}'\n" +
                $"Key6: '{Config["Key6"]}'");
    }
}

下面的命令用來測試鍵替換:

dotnet run -k1 value1 -k2 value2 --alt3=value2 /alt4=value3 --alt5 value5 /alt6 value6

對於使用切換映射的應用程式,調用 CreateDefaultBuilder 不應該傳遞參數。CreateDefaultBuilder 方法的 AddCommandLine 的調用不包括映射切換,沒有方法可以傳遞切換映射的字典給 CreateDefaultBuilder。解決方法是允許 ConfigurationBuilder 方法的 AddCommandLine 同時處理參數和切換映射字典而不是傳遞參數給 CreateDefaultBuilder。

分層配置數據

配置 API 通過使用在配置鍵中的分界符扁平化分層數據來讀取配置數據。

示常式序 (sample download) 包含下面的 appsettings.json 文件:

{
  "Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  },
  "MyKey":  "My appsettings.json Value",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

下面示例 (sample download) 中的程式碼展示了一些配置設置:

public class TestModel : PageModel
{
    // requires using Microsoft.Extensions.Configuration;
    private readonly IConfiguration Configuration;

    public TestModel(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public ContentResult OnGet()
    {
        var myKeyValue = Configuration["MyKey"];
        var title = Configuration["Position:Title"];
        var name = Configuration["Position:Name"];
        var defaultLogLevel = Configuration["Logging:LogLevel:Default"];


        return Content($"MyKey value: {myKeyValue} \n" +
                       $"Title: {title} \n" +
                       $"Name: {name} \n" +
                       $"Default Log Level: {defaultLogLevel}");
    }
}

讀取分層配置數據的首選方式是使用選項模型。更多資訊,查看本文檔中的綁定分層配置數據 (Bind hierarchical configuration data)。

GetSection 和 GetChildren 方法可以用來分離配置數據中的分區和分區中的子部分。這些方法在之後的 GetSection, GetChildren, and Exists 中會描述到。

配置的鍵和值

配置的鍵:

  • 不區分大小寫。例如 ConnectionString 和 connectionstring 被認為是等價的鍵
  • 如果一個鍵和值在多個配置提供器中被設置,最後一個提供器的值將會被使用。更多資訊,查看默認配置 (Default configuration)
  • 分層鍵
    – 在配置 API 內部,一個冒號分隔符 (:) 在所有平台都能工作
    – 在環境變數中,一個冒號分隔符可能不會在所有平台上工作。雙下劃線 (__) 被所有平台支援,並且會被自動的轉換為一個冒號 (:)
    – 在 Azure 鍵倉庫中,分層的鍵使用 — 作為一個分隔符。當秘密數據被載入到應用程式配置的時候,Azure Key Vault configuration provider 自動使用一個冒號 (:) 替換 (–)。
  • ConfigurationBinder 支援綁定數組到在配置鍵中使用數組索引的對象。數組綁定在 Bind an array to a class 部分描述。

配置值:

  • 是字元串
  • Null 值不能存儲在配置中或者綁定到對象

配置提供器

下面的表格中顯示了 ASP.NET Core 應用程式中可以使用的配置提供器

Provider Providers configuration from
Azure Key Vault configuration provider Azure Key Valut
Azure App configuration provider Azure App Configuration
Command-line configuration provider Command-line parameters
Custom configuration provider Custom source
Environment Variables configuration provider Environment variables
File configuration provider INI,JSON,XML 文件
Key-per-file configuration provider 字典文件
Memory configuration provider 記憶體中的集合
User secrets 用戶配置目錄中的文件

配置源的讀取的順序按照它們的配置提供器被指定的順序。在程式碼中對配置提供器排序來滿足應用程式要求的配置源的順序。

一個典型的配置提供器的順序是:

  1. appsettings.json
  2. appsettings.Environment.json
  3. User secrets
  4. 使用 Environment Variables configuration provider 的環境變數
  5. 使用 Command-line configuration provider 的命令行參數

一個常用的實踐是在一系列的配置提供器的最後添加命令行配置提供器,用來覆蓋其它提供器的配置設置

上面的提供器的順序在默認配置 (default configuration) 中使用。

連接字元串前綴

配置 API 對於四種連接字元串環境變數有特殊的處理規則。這些連接字元串會根據應用程式環境解析來配置 Azure 連接字元串。下面表格中的帶有前綴的環境變數在應用程式使用默認配置 (default configuration)或者沒有前綴沒有應用到 AddEnvironmentVariables 的情況下會被載入到應用程式中。

Connection string prefix Provider
CUSTOMCONNSTR_ 自定義提供器
MYSQLCONNSTR_ MySQL
SQLAZURECONNSTR_ Azure SQL Database
SQLCONNSTR_ SQL Server

當一個環境變數被發現並且使用表格中四種前綴的任一種被載入到配置中的時候:

  • 通過移除環境變數的前綴創建配置的鍵,添加一個配置鍵的區域(ConnectionStrings)
  • 一個新的配置的鍵值對被創建,這個鍵值對代表了資料庫連接提供器 (CUSTOMCONNSTR_ 除外,由於沒有固定的提供器)
環境變數鍵 轉換後的配置鍵 提供器配置入口
CUSTOMCONNSTR_{KEY} ConnectionStrings:{KEY} 配置入口沒有創建
MYSQLCONNSTR_{KEY} ConnectionString:{KEY}

Key:ConnectionStrings:

{KEY}_ProviderName:

Value:MySql.DataMySqlClient

SQLAZURECONNSTR_{KEY} ConnectionStrings:{KEY}

Key:ConnectionStrings:

{KEY}_ProviderName:

Value:System.Data.SqlClient

SQLCONNSTR_{KEY} ConnectionStrings:{KEY}

Key:ConnectionStrings:

{KEY}_ProviderName:

Value:System.Data.SqlClient

 文件配置提供器

FileConfigurationProvider 是從文件系統載入配置的基類。下面的配置提供器都從 FileConfigurationProvider 類繼承而來。

INI 配置提供器

IniConfigurationProvider 在運行時從 INI 文件中載入鍵值對的配置。

下面的程式碼清空了所有配置提供器,添加了一些配置提供器:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.Sources.Clear();

                var env = hostingContext.HostingEnvironment;

                config.AddIniFile("MyIniConfig.ini", optional: true, reloadOnChange: true)
                      .AddIniFile($"MyIniConfig.{env.EnvironmentName}.ini",
                                     optional: true, reloadOnChange: true);

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}