ASP.NET Core 的設定Configuration in ASP.NET Core

作者:Luke LathamBy Luke Latham

ASP.NET Core 中的應用程式設定是以由設定提供者所建立的機碼值組為基礎。App configuration in ASP.NET Core is based on key-value pairs established by configuration providers. 設定提供者會從各種設定來源將設定資料讀取到機碼值組中:Configuration providers read configuration data into key-value pairs from a variety of configuration sources:

  • Azure Key VaultAzure Key Vault
  • Azure 應用程式組態Azure App Configuration
  • 命令列引數Command-line arguments
  • 自訂提供者 (已安裝或已建立)Custom providers (installed or created)
  • 目錄檔案Directory files
  • 環境變數Environment variables
  • 記憶體內部 .NET 物件In-memory .NET objects
  • 設定檔Settings files

一般組態提供者案例 (Microsoft.Extensions.Configuration) 的組態套件會以隱含方式包含在架構中。Configuration packages for common configuration provider scenarios (Microsoft.Extensions.Configuration) are included implicitly by the framework.

一般組態提供者案例 (microsoft.Extensions.Configuration) 的組態套件包含在 Microsoft.AspNetCore.App 中繼套件中。Configuration packages for common configuration provider scenarios (Microsoft.Extensions.Configuration) are included in the Microsoft.AspNetCore.App metapackage.

下列程式碼範例與範例應用程式中的程式碼範例使用 Microsoft.Extensions.Configuration 命名空間:Code examples that follow and in the sample app use the Microsoft.Extensions.Configuration namespace:

using Microsoft.Extensions.Configuration;

選項模式是此主題中所述之設定概念的延伸。The options pattern is an extension of the configuration concepts described in this topic. 選項使用類別來代表一組相關的設定。Options use classes to represent groups of related settings. 如需詳細資訊,請參閱 ASP.NET Core 中的選項模式For more information, see ASP.NET Core 中的選項模式.

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

主機與應用程式組態的比較Host versus app configuration

設定及啟動應用程式之前,會先設定及啟動「主機」 。Before the app is configured and started, a host is configured and launched. 主機負責應用程式啟動和存留期管理。The host is responsible for app startup and lifetime management. 應用程式與主機都是使用此主題中所述的設定提供者來設定的。Both the app and the host are configured using the configuration providers described in this topic. 主機組態機碼/值組也會包含在應用程式的組態中。Host configuration key-value pairs are also included in the app's configuration. 如需有關當建置主機時如何使用設定提供者的詳細資訊,以及設定來源如何影響主機設定的詳細資訊,請參閱 ASP.NET Core 基本概念For more information on how the configuration providers are used when the host is built and how configuration sources affect host configuration, see ASP.NET Core 基本概念.

預設的組態Default configuration

以 ASP.NET Core dotnet new 範本為基礎的 Web 應用程式,會在建置主機時呼叫 CreateDefaultBuilderWeb apps based on the ASP.NET Core dotnet new templates call CreateDefaultBuilder when building a host. CreateDefaultBuilder 會以下列順序提供應用程式的預設組態:CreateDefaultBuilder provides default configuration for the app in the following order:

下列項目適用於使用一般主機的應用程式。The following applies to apps using the Generic Host. 如需使用 Web 主機時預設組態的詳細資料,請參閱本主題的 ASP.NET Core 2.2 版本For details on the default configuration when using the Web Host, see the ASP.NET Core 2.2 version of this topic.

  • 主機組態的提供來源:Host configuration is provided from:
  • 已建立 Web 主機預設組態 (ConfigureWebHostDefaults):Web Host default configuration is established (ConfigureWebHostDefaults):
    • Kestrel 會用作為網頁伺服器,並使用應用程式的組態提供者來設定。Kestrel is used as the web server and configured using the app's configuration providers.
    • 新增主機篩選中介軟體。Add Host Filtering Middleware.
    • 如果 ASPNETCORE_FORWARDEDHEADERS_ENABLED 環境變數設定為 true,則會新增轉接的標頭中介軟體。Add Forwarded Headers Middleware if the ASPNETCORE_FORWARDEDHEADERS_ENABLED environment variable is set to true.
    • 啟用 IIS 整合。Enable IIS integration.
  • 應用程式設定的提供來源:App configuration is provided from:

以 ASP.NET Core dotnet new 範本為基礎的 Web 應用程式,會在建置主機時呼叫 CreateDefaultBuilderWeb apps based on the ASP.NET Core dotnet new templates call CreateDefaultBuilder when building a host. CreateDefaultBuilder 會以下列順序提供應用程式的預設組態:CreateDefaultBuilder provides default configuration for the app in the following order:

下列項目適用於使用 Web 主機的應用程式。The following applies to apps using the Web Host. 如需使用一般主機時預設組態的詳細資料,請參閱本主題的最新版本For details on the default configuration when using the Generic Host, see the latest version of this topic.

安全性Security

採用下列做法來保護敏感性組態資料:Adopt the following practices to secure sensitive configuration data:

  • 永遠不要將密碼或其他敏感性資料儲存在設定提供者程式碼或純文字設定檔中。Never store passwords or other sensitive data in configuration provider code or in plain text configuration files.
  • 不要在開發或測試環境中使用生產環境祕密。Don't use production secrets in development or test environments.
  • 請在專案外部指定祕密,以防止其意外認可至開放原始碼存放庫。Specify secrets outside of the project so that they can't be accidentally committed to a source code repository.

如需詳細資訊,請參閱下列主題:For more information, see the following topics:

Azure Key Vault 可安全地儲存 ASP.NET Core 應用程式的應用程式祕密。Azure Key Vault safely stores app secrets for ASP.NET Core apps. 如需詳細資訊,請參閱 ASP.NET Core 中的 Azure Key Vault 設定提供者For more information, see ASP.NET Core 中的 Azure Key Vault 設定提供者.

階層式設定資料Hierarchical configuration data

設定 API 可在設定機碼中使用分隔符號來壓平合併階層式資料,以管理階層式設定資料。The Configuration API is capable of maintaining hierarchical configuration data by flattening the hierarchical data with the use of a delimiter in the configuration keys.

在下列 JSON 檔案中,兩個區段的結構式階層中有四個機碼存在:In the following JSON file, four keys exist in a structured hierarchy of two sections:

{
  "section0": {
    "key0": "value",
    "key1": "value"
  },
  "section1": {
    "key0": "value",
    "key1": "value"
  }
}

當該檔案被讀入設定之後,會建立唯一機碼來維護設定來源的原始階層式資料結構。When the file is read into configuration, unique keys are created to maintain the original hierarchical data structure of the configuration source. 系統會使用冒號 (:) 將區段與機碼壓平合併以維護原始結構:The sections and keys are flattened with the use of a colon (:) to maintain the original structure:

  • section0:key0section0:key0
  • section0:key1section0:key1
  • section1:key0section1:key0
  • section1:key1section1:key1

GetSectionGetChildren 方法可用來在設定資料中隔離區段與區段的子系。GetSection and GetChildren methods are available to isolate sections and children of a section in the configuration data. GetSection,、 GetChildren 與 Exists 中說明這些方法。These methods are described later in GetSection, GetChildren, and Exists.

慣例Conventions

來源和提供者Sources and providers

在應用程式啟動時,會依照設定來源的設定提供者的指定順序讀入設定來源。At app startup, configuration sources are read in the order that their configuration providers are specified.

實作變更偵測的組態提供者能夠在基礎設定變更時重新載入組態。Configuration providers that implement change detection have the ability to reload configuration when an underlying setting is changed. 例如,檔案組態提供者 (將於本主題稍後討論) 和 Azure Key Vault 組態提供者均會實作變更偵測。For example, the File Configuration Provider (described later in this topic) and the Azure Key Vault Configuration Provider implement change detection.

您可以在應用程式的相依性插入 (DI) 容器中找到 IConfigurationIConfiguration is available in the app's dependency injection (DI) container. IConfiguration 可插入 Razor Pages PageModel 來取得類別的組態:IConfiguration can be injected into a Razor Pages PageModel to obtain configuration for the class:

public class IndexModel : PageModel
{
    private readonly IConfiguration _config;

    public IndexModel(IConfiguration config)
    {
        _config = config;
    }

    // The _config local variable is used to obtain configuration 
    // throughout the class.
}

設定提供者無法使用 DI,因為當它們由主機設定時,它無法使用。Configuration providers can't utilize DI, as it's not available when they're set up by the host.

按鍵Keys

設定機碼會採用下列慣例:Configuration keys adopt the following conventions:

  • 機碼區分大小寫。Keys are case-insensitive. 例如,ConnectionStringconnectionstring 會被視為相等的機碼。For example, ConnectionString and connectionstring are treated as equivalent keys.
  • 若相同機碼的值是由相同或不同設定提供者設定,在機碼上設定的最後一個值是所使用的值。If a value for the same key is set by the same or different configuration providers, the last value set on the key is the value used.
  • 階層式機碼Hierarchical keys
    • 在設定 API 內,冒號分隔字元 (:) 可在所有平台上運作。Within the Configuration API, a colon separator (:) works on all platforms.
    • 在環境變數中,冒號分隔字元可能無法在所有平台上運作。In environment variables, a colon separator may not work on all platforms. 所有平台都支援雙底線 (__),且會自動轉換為冒號。A double underscore (__) is supported by all platforms and is automatically converted into a colon.
    • 在 Azure Key Vault 中,階層式機碼使用 -- (兩個破折號) 來做為分隔符號。In Azure Key Vault, hierarchical keys use -- (two dashes) as a separator. 您必須提供程式碼,在祕密載入到應用程式的設定時將破折號取代為冒號。You must provide code to replace the dashes with a colon when the secrets are loaded into the app's configuration.
  • ConfigurationBinder 支援在設定機碼中使用陣列索引將陣列繫結到物件。The ConfigurationBinder supports binding arrays to objects using array indices in configuration keys. 將陣列繫結到類別一節說明陣列繫結。Array binding is described in the Bind an array to a class section.

Values

設定值會採用下列慣例:Configuration values adopt the following conventions:

  • 值是字串。Values are strings.
  • Null 值無法存放在設定中或繫結到物件。Null values can't be stored in configuration or bound to objects.

提供者Providers

下表顯示可供 ASP.NET Core 應用程式使用的設定提供者。The following table shows the configuration providers available to ASP.NET Core apps.

提供者Provider 從…提供設定Provides configuration from…
Azure Key Vault 設定提供者 (安全性主題)Azure Key Vault Configuration Provider (Security topics) Azure Key VaultAzure Key Vault
Azure 應用程式組態提供者 (Azure 文件)Azure App Configuration Provider (Azure documentation) Azure 應用程式組態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)Files (INI, JSON, XML)
每個檔案機碼的設定提供者Key-per-file Configuration Provider 目錄檔案Directory files
記憶體設定提供者Memory Configuration Provider 記憶體內集合In-memory collections
使用者祕密 (祕密管理員) (安全性主題)User secrets (Secret Manager) (Security topics) 使用者設定檔目錄中的檔案File in the user profile directory

在啟動時,會依照設定來源的設定提供者的指定順序讀入設定來源。Configuration sources are read in the order that their configuration providers are specified at startup. 此主題中所述的設定提供者是以字母順序描述,而非以您的程式碼安排它們的順序。The configuration providers described in this topic are described in alphabetical order, not in the order that your code may arrange them. 在您的程式碼中針對底層設定來源的優先順序,為設定提供者排序。Order configuration providers in your code to suit your priorities for the underlying configuration sources.

典型的設定提供者順序是:A typical sequence of configuration providers is:

  1. 檔案 (appsettings.jsonappsettings.{Environment}.json,其中 {Environment} 是應用程式的目前裝載環境)Files (appsettings.json, appsettings.{Environment}.json, where {Environment} is the app's current hosting environment)
  2. Azure Key VaultAzure Key Vault
  3. 使用者祕密 (祕密管理員) (僅限開發環境)User secrets (Secret Manager) (Development environment only)
  4. 環境變數Environment variables
  5. 命令列引數Command-line arguments

將命令列組態提供者放在提供者序列結尾是常見做法,因為這樣可以讓命令列引數覆寫由其他提供者所設定的組態。A common practice is to position the Command-line Configuration Provider last in a series of providers to allow command-line arguments to override configuration set by the other providers.

當您使用 CreateDefaultBuilder 初始化新的主機建立器時,會使用上述的提供者序列。The preceding sequence of providers is used when you initialize a new host builder with CreateDefaultBuilder. 如需詳細資訊,請參閱<預設組態>一節。For more information, see the Default configuration section.

使用 ConfigureHostConfiguration 設定主機建立器Configure the host builder with ConfigureHostConfiguration

若要設定主機建立器,請呼叫 ConfigureHostConfiguration 並提供組態。To configure the host builder, call ConfigureHostConfiguration and supply the configuration. ConfigureHostConfiguration 用於初始化 IHostEnvironment,以便稍後在建置程序中使用。ConfigureHostConfiguration is used to initialize the IHostEnvironment for use later in the build process. ConfigureHostConfiguration 可以多次呼叫,其結果是累加的。ConfigureHostConfiguration can be called multiple times with additive results.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration((hostingContext, config) =>
        {
            var dict = new Dictionary<string, string>
            {
                {"MemoryCollectionKey1", "value1"},
                {"MemoryCollectionKey2", "value2"}
            };

            config.AddInMemoryCollection(dict);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

使用 UseConfiguration 設定主機建立器Configure the host builder with UseConfiguration

若要設定主機建立器,請使用該組態在主機建立器上呼叫 UseConfigurationTo configure the host builder, call UseConfiguration on the host builder with the configuration.

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    var dict = new Dictionary<string, string>
    {
        {"MemoryCollectionKey1", "value1"},
        {"MemoryCollectionKey2", "value2"}
    };

    var config = new ConfigurationBuilder()
        .AddInMemoryCollection(dict)
        .Build();

    return WebHost.CreateDefaultBuilder(args)
        .UseConfiguration(config)
        .UseStartup<Startup>();
}

ConfigureAppConfigurationConfigureAppConfiguration

建置主機時呼叫 ConfigureAppConfiguration 以指定應用程式的設定提供者,以及由 CreateDefaultBuilder 自動新增的設定提供者:Call ConfigureAppConfiguration when building the host to specify the app's configuration providers in addition to those added automatically by CreateDefaultBuilder:

public class Program
{
    public static Dictionary<string, string> arrayDict = 
        new Dictionary<string, string>
        {
            {"array:entries:0", "value0"},
            {"array:entries:1", "value1"},
            {"array:entries:2", "value2"},
            {"array:entries:4", "value4"},
            {"array:entries:5", "value5"}
        };

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddInMemoryCollection(arrayDict);
                config.AddJsonFile(
                    "json_array.json", optional: false, reloadOnChange: false);
                config.AddJsonFile(
                    "starship.json", optional: false, reloadOnChange: false);
                config.AddXmlFile(
                    "tvshow.xml", optional: false, reloadOnChange: false);
                config.AddEFConfiguration(
                    options => options.UseInMemoryDatabase("InMemoryDb"));
                config.AddCommandLine(args);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
public class Program
{
    public static Dictionary<string, string> arrayDict = 
        new Dictionary<string, string>
        {
            {"array:entries:0", "value0"},
            {"array:entries:1", "value1"},
            {"array:entries:2", "value2"},
            {"array:entries:4", "value4"},
            {"array:entries:5", "value5"}
        };

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddInMemoryCollection(arrayDict);
                config.AddJsonFile(
                    "json_array.json", optional: false, reloadOnChange: false);
                config.AddJsonFile(
                    "starship.json", optional: false, reloadOnChange: false);
                config.AddXmlFile(
                    "tvshow.xml", optional: false, reloadOnChange: false);
                config.AddEFConfiguration(
                    options => options.UseInMemoryDatabase("InMemoryDb"));
                config.AddCommandLine(args);
            })
            .UseStartup<Startup>();
}

使用命令列引數覆寫先前的組態Override previous configuration with command-line arguments

若要提供可使用命令列引數覆寫的應用程式組態,請最後呼叫 AddCommandLineTo provide app configuration that can be overridden with command-line arguments, call AddCommandLine last:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    // Call other providers here
    config.AddCommandLine(args);
})

在應用程式啟動期間使用組態Consume configuration during app startup

應用程式啟動期間,可以使用 ConfigureAppConfiguration 中為應用程式提供的組態,包括 Startup.ConfigureServicesConfiguration supplied to the app in ConfigureAppConfiguration is available during the app's startup, including Startup.ConfigureServices. 如需詳細資訊,請參閱在啟動期間存取組態一節。For more information, see the Access configuration during startup section.

命令列設定提供者Command-line Configuration Provider

CommandLineConfigurationProvider 會在執行階段從命令列引數機碼值組載入設定。The CommandLineConfigurationProvider loads configuration from command-line argument key-value pairs at runtime.

為了啟用命令列設定,AddCommandLine 延伸模組方法會在 ConfigurationBuilder 的執行個體上呼叫。To activate command-line configuration, the AddCommandLine extension method is called on an instance of ConfigurationBuilder.

呼叫 CreateDefaultBuilder(string []) 時,會自動呼叫 AddCommandLineAddCommandLine is automatically called when CreateDefaultBuilder(string []) is called. 如需詳細資訊,請參閱<預設組態>一節。For more information, see the Default configuration section.

CreateDefaultBuilder 也會載入:CreateDefaultBuilder also loads:

  • appsettings.jsonappsettings.{Environment}.json 檔案載入其他選擇性組態。Optional configuration from appsettings.json and appsettings.{Environment}.json files.
  • 開發環境中的使用者祕密 (祕密管理員)User secrets (Secret Manager) in the Development environment.
  • 環境變數。Environment variables.

CreateDefaultBuilder 會最後才新增命令列設定提供者。CreateDefaultBuilder adds the Command-line Configuration Provider last. 在執行階段傳遞的命令列引數會覆寫由其它提供者所設定的設定。Command-line arguments passed at runtime override configuration set by the other providers.

CreateDefaultBuilder 會在建構主機時執行作業。CreateDefaultBuilder acts when the host is constructed. 因此,由CreateDefaultBuilder 啟用的命令列設定可以影響主機的設定方式。Therefore, command-line configuration activated by CreateDefaultBuilder can affect how the host is configured.

針對以 ASP.NET Core 範本為基礎的應用程式,AddCommandLine 已由 CreateDefaultBuilder 呼叫。For apps based on the ASP.NET Core templates, AddCommandLine has already been called by CreateDefaultBuilder. 若要新增其他組態提供者並維持能夠使用命令列引數覆寫這些提供者組態的能力,請在 ConfigureAppConfiguration 中呼叫應用程式的其他提供者,且最後呼叫 AddCommandLineTo add additional configuration providers and maintain the ability to override configuration from those providers with command-line arguments, call the app's additional providers in ConfigureAppConfiguration and call AddCommandLine last.

.ConfigureAppConfiguration((hostingContext, config) =>
{
    // Call other providers here
    config.AddCommandLine(args);
})

範例Example

範例應用程式利用靜態方便方法 CreateDefaultBuilder 的優勢來建置主機,這包括對 AddCommandLine 的呼叫。The sample app takes advantage of the static convenience method CreateDefaultBuilder to build the host, which includes a call to AddCommandLine.

  1. 從專案目錄中開啟命令提示字元。Open a command prompt in the project's directory.
  2. 提供命令列引數給 dotnet run 命令 dotnet run CommandLineKey=CommandLineValueSupply a command-line argument to the dotnet run command, dotnet run CommandLineKey=CommandLineValue.
  3. 在應用程式執行之後,開啟瀏覽器以瀏覽位於 http://localhost:5000 的應用程式。After the app is running, open a browser to the app at http://localhost:5000.
  4. 觀察輸出是否包含提供給 dotnet run 之設定命令列引數的機碼值組。Observe that the output contains the key-value pair for the configuration command-line argument provided to dotnet run.

引數Arguments

當值後面接著空格時,值必須接著等號 (=),或機碼必須有前置詞 (--/)。The value must follow an equals sign (=), or the key must have a prefix (-- or /) when the value follows a space. 如果使用等號 (例如 CommandLineKey=),則不需要此值。The value isn't required if an equals sign is used (for example, CommandLineKey=).

索引鍵前置字元Key prefix 範例Example
沒有前置字元No prefix CommandLineKey1=value1
雙虛線 (--)Two dashes (--) --CommandLineKey2=value2--CommandLineKey2 value2--CommandLineKey2=value2, --CommandLineKey2 value2
正斜線 (/)Forward slash (/) /CommandLineKey3=value3/CommandLineKey3 value3/CommandLineKey3=value3, /CommandLineKey3 value3

在相同的命令中,請不要混合使用等號搭配使用空格之機碼值組的命令列引數。Within the same command, don't mix command-line argument key-value pairs that use an equals sign with key-value pairs that use a space.

範例命令:Example commands:

dotnet run CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3
dotnet run --CommandLineKey1 value1 /CommandLineKey2 value2
dotnet run CommandLineKey1= CommandLineKey2=value2

切換對應Switch mappings

參數對應允許索引鍵名稱取代邏輯。Switch mappings allow key name replacement logic. 當您使用 ConfigurationBuilder 手動建置設定時,可以提供切換取代的字典給 AddCommandLine 方法。When you manually build configuration with a ConfigurationBuilder, you can provide a dictionary of switch replacements to the AddCommandLine method.

使用切換對應字典時,會檢查字典中是否有任何索引鍵符合命令列引數所提供的索引鍵。When the switch mappings dictionary is used, the dictionary is checked for a key that matches the key provided by a command-line argument. 如果在字典中找到命令列索引鍵,則會傳回字典值 (索引鍵取代) 以在應用程式的設定中設定機碼值組。If the command-line key is found in the dictionary, the dictionary value (the key replacement) is passed back to set the key-value pair into the app's configuration. 所有前面加上單虛線 (-) 的命令列索引鍵都需要切換對應。A switch mapping is required for any command-line key prefixed with a single dash (-).

切換對應字典索引鍵規則:Switch mappings dictionary key rules:

  • 切換必須以單虛線 (-) 或雙虛線 (--) 開頭。Switches must start with a dash (-) or double-dash (--).
  • 切換對應字典不能包含重複索引鍵。The switch mappings dictionary must not contain duplicate keys.

建立切換對應字典。Create a switch mappings dictionary. 下列範例會建立兩個切換對應:In the following example, two switch mappings are created:

public static readonly Dictionary<string, string> _switchMappings = 
    new Dictionary<string, string>
    {
        { "-CLKey1", "CommandLineKey1" },
        { "-CLKey2", "CommandLineKey2" }
    };

建立主機時,請使用切換對應字典呼叫 AddCommandLineWhen the host is built, call AddCommandLine with the switch mappings dictionary:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddCommandLine(args, _switchMappings);
})

針對使用切換對應的應用程式,呼叫 CreateDefaultBuilder 不應傳遞引數。For apps that use switch mappings, the call to CreateDefaultBuilder shouldn't pass arguments. CreateDefaultBuilder 方法的 AddCommandLine 呼叫不包括對應的切換,且沒有任何方式可以將切換對應字典傳遞給 CreateDefaultBuilderThe CreateDefaultBuilder method's AddCommandLine call doesn't include mapped switches, and there's no way to pass the switch mapping dictionary to CreateDefaultBuilder. 解決方案並非將引數傳遞給 CreateDefaultBuilder,而是允許 ConfigurationBuilder 方法的 AddCommandLine 方法同時處理引數與切換對應字典。The solution isn't to pass the arguments to CreateDefaultBuilder but instead to allow the ConfigurationBuilder method's AddCommandLine method to process both the arguments and the switch mapping dictionary.

建立切換對應字典之後,它會包含下表中所示的資料。After the switch mappings dictionary is created, it contains the data shown in the following table.

KeyKey Value
-CLKey1 CommandLineKey1
-CLKey2 CommandLineKey2

若啟動應用程式時使用切換對應機碼,設定會接收由字典提供之機碼上的設定值:If the switch-mapped keys are used when starting the app, configuration receives the configuration value on the key supplied by the dictionary:

dotnet run -CLKey1=value1 -CLKey2=value2

執行上述命令之後,設定包含下表中顯示的值。After running the preceding command, configuration contains the values shown in the following table.

KeyKey Value
CommandLineKey1 value1
CommandLineKey2 value2

環境變數設定提供者Environment Variables Configuration Provider

EnvironmentVariablesConfigurationProvider 會在執行階段從環境變數機碼值組載入設定。The EnvironmentVariablesConfigurationProvider loads configuration from environment variable key-value pairs at runtime.

若要啟用環境變數設定,請在 ConfigurationBuilder 的執行個體上呼叫 AddEnvironmentVariables 延伸模組方法。To activate environment variables configuration, call the AddEnvironmentVariables extension method on an instance of ConfigurationBuilder.

在環境變數中搭配階層式機碼使用時,冒號分隔字元 (:) 可能無法在所有平台上運作 (例如 Bash)。When working with hierarchical keys in environment variables, a colon separator (:) may not work on all platforms (for example, Bash). 所有平台都支援雙底線 (__),且會自動由冒號取代。A double underscore (__) is supported by all platforms and is automatically replaced by a colon.

Azure App Service 允許您在 Azure 入口網站中設定環境變數,以使用「環境變數設定提供者」覆寫應用程式設定。Azure App Service permits you to set environment variables in the Azure Portal that can override app configuration using the Environment Variables Configuration Provider. 如需詳細資訊,請參閱 Azure App:使用 Azure 入口網站覆寫應用程式設定For more information, see Azure Apps: Override app configuration using the Azure Portal.

使用一般主機初始化新的主機建立器並呼叫 CreateDefaultBuilder 時,可使用 AddEnvironmentVariables主機組態載入字首為 DOTNET_ 的環境變數。AddEnvironmentVariables is used to load environment variables prefixed with DOTNET_ for host configuration when a new host builder is initialized with the Generic Host and CreateDefaultBuilder is called. 如需詳細資訊,請參閱<預設組態>一節。For more information, see the Default configuration section.

使用 Web 主機初始化新的主機建立器並呼叫 CreateDefaultBuilder 時,可使用 AddEnvironmentVariables主機組態載入字首為 ASPNETCORE_ 的環境變數。AddEnvironmentVariables is used to load environment variables prefixed with ASPNETCORE_ for host configuration when a new host builder is initialized with the Web Host and CreateDefaultBuilder is called. 如需詳細資訊,請參閱<預設組態>一節。For more information, see the Default configuration section.

CreateDefaultBuilder 也會載入:CreateDefaultBuilder also loads:

  • 來自無首碼之環境變數的應用程式組態 (在未提供首碼的情況下呼叫 AddEnvironmentVariables)。App configuration from unprefixed environment variables by calling AddEnvironmentVariables without a prefix.
  • appsettings.jsonappsettings.{Environment}.json 檔案載入其他選擇性組態。Optional configuration from appsettings.json and appsettings.{Environment}.json files.
  • 開發環境中的使用者祕密 (祕密管理員)User secrets (Secret Manager) in the Development environment.
  • 命令列引數。Command-line arguments.

從使用者祕密與 appsettings 檔案建立設定之後,會呼叫「環境變數設定提供者」。The Environment Variables Configuration Provider is called after configuration is established from user secrets and appsettings files. 在此位置呼叫提供者可讓系統在執行階段讀取環境變數,以覆寫由使用者祕密與 appsettings 檔案所設定的設定。Calling the provider in this position allows the environment variables read at runtime to override configuration set by user secrets and appsettings files.

如果您需要從其他環境變數提供應用程式設定,請呼叫 ConfigureAppConfiguration 中的應用程式其他提供者,並呼叫具有該前置詞的 AddEnvironmentVariablesIf you need to provide app configuration from additional environment variables, call the app's additional providers in ConfigureAppConfiguration and call AddEnvironmentVariables with the prefix.

.ConfigureAppConfiguration((hostingContext, config) =>
{
    // Call additional providers here as needed.
    // Call AddEnvironmentVariables last if you need to allow
    // environment variables to override values from other 
    // providers.
    config.AddEnvironmentVariables(prefix: "PREFIX_");
})
}

範例Example

範例應用程式利用靜態方便方法 CreateDefaultBuilder 的優勢來建置主機,這包括對 AddEnvironmentVariables 的呼叫。The sample app takes advantage of the static convenience method CreateDefaultBuilder to build the host, which includes a call to AddEnvironmentVariables.

  1. 執行範例應用程式。Run the sample app. 開啟瀏覽器以瀏覽位於 http://localhost:5000 的應用程式。Open a browser to the app at http://localhost:5000.
  2. 觀察輸出是否包含環境變數 ENVIRONMENT 的機碼值組。Observe that the output contains the key-value pair for the environment variable ENVIRONMENT. 值反映應用程式執行所在環境,在本機執行時,通常是 DevelopmentThe value reflects the environment in which the app is running, typically Development when running locally.

為縮短由應用程式轉譯的環境變數清單,應用程式會篩選環境變數。To keep the list of environment variables rendered by the app short, the app filters environment variables. 請參閱範例應用程式的 Pages/Index.cshtml.cs 檔案。See the sample app's Pages/Index.cshtml.cs file.

若想要將所有環境變數公開給應用程式使用,請將 Pages/Index.cshtml.cs 中的 FilteredConfiguration 變更為下面這樣:If you wish to expose all of the environment variables available to the app, change the FilteredConfiguration in Pages/Index.cshtml.cs to the following:

FilteredConfiguration = _config.AsEnumerable();

首碼Prefixes

當您將前置詞套用到 AddEnvironmentVariables 方法時,會篩選載入到應用程式設定中的環境變數。Environment variables loaded into the app's configuration are filtered when you supply a prefix to the AddEnvironmentVariables method. 例如,若要篩選前置詞為 CUSTOM_ 的環境變數,請提供前置詞給設定提供者:For example, to filter environment variables on the prefix CUSTOM_, supply the prefix to the configuration provider:

var config = new ConfigurationBuilder()
    .AddEnvironmentVariables("CUSTOM_")
    .Build();

建立設定機碼值組時,會移除前置詞。The prefix is stripped off when the configuration key-value pairs are created.

建立主機建立器時,主機組態由環境變數提供。When the host builder is created, host configuration is provided by environment variables. 如需這些環境變數所用前置詞的詳細資訊,請參閱<預設組態>一節。For more information on the prefix used for these environment variables, see the Default configuration section.

連接字串前置詞Connection string prefixes

設定 API 四個連接字串環境變數的特殊處理規則,這些這些環境變數牽涉到針對應用程式環境設定 Azure 連接字串。The Configuration API has special processing rules for four connection string environment variables involved in configuring Azure connection strings for the app environment. 若將前置詞提供給 AddEnvironmentVariables具有下表顯示之前置詞的環境變數。Environment variables with the prefixes shown in the table are loaded into the app if no prefix is supplied to AddEnvironmentVariables.

連接字串前置詞Connection string prefix 提供者Provider
CUSTOMCONNSTR_ 自訂提供者Custom provider
MYSQLCONNSTR_ MySQLMySQL
SQLAZURECONNSTR_ Azure SQL DatabaseAzure SQL Database
SQLCONNSTR_ SQL ServerSQL Server

當探索到具有下表所顯示之任何四個前置詞的環境變數並將其載入到設定中時:When an environment variable is discovered and loaded into configuration with any of the four prefixes shown in the table:

  • 會透過移除環境變數前置詞並新增設定機碼區段 (ConnectionStrings) 來移除具有下表顯示之前置詞的環境變數。The configuration key is created by removing the environment variable prefix and adding a configuration key section (ConnectionStrings).
  • 會建立新的設定機碼值組以代表資料庫連線提供者 (CUSTOMCONNSTR_ 除外,這沒有所述提供者)。A new configuration key-value pair is created that represents the database connection provider (except for CUSTOMCONNSTR_, which has no stated provider).
環境變數機碼Environment variable key 已轉換的設定機碼Converted configuration key 提供者設定項目Provider configuration entry
CUSTOMCONNSTR_<KEY> ConnectionStrings:<KEY> 設定項目未建立。Configuration entry not created.
MYSQLCONNSTR_<KEY> ConnectionStrings:<KEY> 機碼:ConnectionStrings:<KEY>_ProviderNameKey: ConnectionStrings:<KEY>_ProviderName:
值:MySql.Data.MySqlClientValue: MySql.Data.MySqlClient
SQLAZURECONNSTR_<KEY> ConnectionStrings:<KEY> 機碼:ConnectionStrings:<KEY>_ProviderNameKey: ConnectionStrings:<KEY>_ProviderName:
值:System.Data.SqlClientValue: System.Data.SqlClient
SQLCONNSTR_<KEY> ConnectionStrings:<KEY> 機碼:ConnectionStrings:<KEY>_ProviderNameKey: ConnectionStrings:<KEY>_ProviderName:
值:System.Data.SqlClientValue: System.Data.SqlClient

檔案設定提供者File Configuration Provider

FileConfigurationProvider 是用於從檔案系統載入設定的基底類別。FileConfigurationProvider is the base class for loading configuration from the file system. 下列設定提供者專用於特定檔案類型:The following configuration providers are dedicated to specific file types:

INI 設定提供者INI Configuration Provider

IniConfigurationProvider 會在執行階段從 INI 檔案機碼值組載入設定。The IniConfigurationProvider loads configuration from INI file key-value pairs at runtime.

若要啟用 INI 檔案設定,請在 ConfigurationBuilder 的執行個體上呼叫 AddIniFile 延伸模組方法。To activate INI file configuration, call the AddIniFile extension method on an instance of ConfigurationBuilder.

冒號可用來做為 INI 檔案設定中的區段分隔符號。The colon can be used to as a section delimiter in INI file configuration.

多載允許指定:Overloads permit specifying:

  • 檔案是否為選擇性。Whether the file is optional.
  • 檔案變更時是否要重新載入設定。Whether the configuration is reloaded if the file changes.
  • IFileProvider 是用於存取該檔案。The IFileProvider used to access the file.

建置主機時呼叫 ConfigureAppConfiguration 以指定應用程式的設定:Call ConfigureAppConfiguration when building the host to specify the app's configuration:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.SetBasePath(Directory.GetCurrentDirectory());
    config.AddIniFile(
        "config.ini", optional: true, reloadOnChange: true);
})

透過 SetBasePath 設定基底路徑。The base path is set with SetBasePath.

INI 設定檔的一般範例:A generic example of an INI configuration file:

[section0]
key0=value
key1=value

[section1]
subsection:key=value

[section2:subsection0]
key=value

[section2:subsection1]
key=value

先前的設定檔會使用 value 載入下列機碼:The previous configuration file loads the following keys with value:

  • section0:key0section0:key0
  • section0:key1section0:key1
  • section1:subsection:keysection1:subsection:key
  • section2:subsection0:keysection2:subsection0:key
  • section2:subsection1:keysection2:subsection1:key

JSON 設定提供者JSON Configuration Provider

JsonConfigurationProvider 會在執行階段從 JSON 檔案機碼值組載入設定。The JsonConfigurationProvider loads configuration from JSON file key-value pairs during runtime.

若要啟用 JSON 檔案設定,請在 ConfigurationBuilder 的執行個體上呼叫 AddJsonFile 延伸模組方法。To activate JSON file configuration, call the AddJsonFile extension method on an instance of ConfigurationBuilder.

多載允許指定:Overloads permit specifying:

  • 檔案是否為選擇性。Whether the file is optional.
  • 檔案變更時是否要重新載入設定。Whether the configuration is reloaded if the file changes.
  • IFileProvider 是用於存取該檔案。The IFileProvider used to access the file.

當您使用 CreateDefaultBuilder 初始化新的主機建立器時,會自動呼叫 AddJsonFile 兩次。AddJsonFile is automatically called twice when you initialize a new host builder with CreateDefaultBuilder. 會呼叫此方法以從下列位置載入設定:The method is called to load configuration from:

  • appsettings.json – 會先讀取此檔案。appsettings.json – This file is read first. 檔案的環境版本可以覆寫由 appsettings.json 檔案提供的值。The environment version of the file can override the values provided by the appsettings.json file.
  • appsettings.{Environment}.json – 檔案的環境版本是根據 IHostingEnvironment.EnvironmentName 來載入的。appsettings.{Environment}.json – The environment version of the file is loaded based on the IHostingEnvironment.EnvironmentName.

如需詳細資訊,請參閱<預設組態>一節。For more information, see the Default configuration section.

CreateDefaultBuilder 也會載入:CreateDefaultBuilder also loads:

會先建立 JSON 設定提供者。The JSON Configuration Provider is established first. 因此,使用者祕密、環境變數與命令列引數會覆寫由 appsettings 檔案設定的設定。Therefore, user secrets, environment variables, and command-line arguments override configuration set by the appsettings files.

在建置主機時,呼叫 ConfigureAppConfiguration 以指定檔案 (除了 appsettings.jsonappsettings.{Environment}.json 以外) 的應用程式設定:Call ConfigureAppConfiguration when building the host to specify the app's configuration for files other than appsettings.json and appsettings.{Environment}.json:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.SetBasePath(Directory.GetCurrentDirectory());
    config.AddJsonFile(
        "config.json", optional: true, reloadOnChange: true);
})

透過 SetBasePath 設定基底路徑。The base path is set with SetBasePath.

範例Example

範例應用程式利用靜態方便方法 CreateDefaultBuilder 的優勢來建置主機,這包括對 AddJsonFile 的兩次呼叫。The sample app takes advantage of the static convenience method CreateDefaultBuilder to build the host, which includes two calls to AddJsonFile. appsettings.jsonappsettings.{Environment}.json 載入設定。Configuration is loaded from appsettings.json and appsettings.{Environment}.json.

  1. 執行範例應用程式。Run the sample app. 開啟瀏覽器以瀏覽位於 http://localhost:5000 的應用程式。Open a browser to the app at http://localhost:5000.
  2. 觀察輸出是否包含表格中所顯示之設定的機碼值組 (視環境而定)。Observe that the output contains key-value pairs for the configuration shown in the table depending on the environment. 記錄設定機碼會使用冒號 (:) 做為階層式分隔符號。Logging configuration keys use the colon (:) as a hierarchical separator.
KeyKey 開發值Development Value 生產值Production Value
Logging:LogLevel:SystemLogging:LogLevel:System 資訊Information 資訊Information
Logging:LogLevel:MicrosoftLogging:LogLevel:Microsoft 資訊Information 資訊Information
Logging:LogLevel:DefaultLogging:LogLevel:Default 偵錯Debug 錯誤Error
AllowedHostsAllowedHosts * *

XML 設定提供者XML Configuration Provider

XmlConfigurationProvider 會在執行階段從 XML 檔案機碼值組載入設定。The XmlConfigurationProvider loads configuration from XML file key-value pairs at runtime.

若要啟用 XML 檔案設定,請在 ConfigurationBuilder 的執行個體上呼叫 AddXmlFile 延伸模組方法。To activate XML file configuration, call the AddXmlFile extension method on an instance of ConfigurationBuilder.

多載允許指定:Overloads permit specifying:

  • 檔案是否為選擇性。Whether the file is optional.
  • 檔案變更時是否要重新載入設定。Whether the configuration is reloaded if the file changes.
  • IFileProvider 是用於存取該檔案。The IFileProvider used to access the file.

建立設定機碼值組時,會忽略設定檔案的根節點。The root node of the configuration file is ignored when the configuration key-value pairs are created. 請勿在檔案中指定文件類型定義 (DTD) 或命名空間。Don't specify a Document Type Definition (DTD) or namespace in the file.

建置主機時呼叫 ConfigureAppConfiguration 以指定應用程式的設定:Call ConfigureAppConfiguration when building the host to specify the app's configuration:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.SetBasePath(Directory.GetCurrentDirectory());
    config.AddXmlFile(
        "config.xml", optional: true, reloadOnChange: true);
})

透過 SetBasePath 設定基底路徑。The base path is set with SetBasePath.

XML 設定檔可以針對重複的區段使用相異元素名稱:XML configuration files can use distinct element names for repeating sections:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <section0>
    <key0>value</key0>
    <key1>value</key1>
  </section0>
  <section1>
    <key0>value</key0>
    <key1>value</key1>
  </section1>
</configuration>

先前的設定檔會使用 value 載入下列機碼:The previous configuration file loads the following keys with value:

  • section0:key0section0:key0
  • section0:key1section0:key1
  • section1:key0section1:key0
  • section1:key1section1:key1

name 屬性是用來區別元素,則可以重複那些使用相同元素名稱的元素:Repeating elements that use the same element name work if the name attribute is used to distinguish the elements:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <section name="section0">
    <key name="key0">value</key>
    <key name="key1">value</key>
  </section>
  <section name="section1">
    <key name="key0">value</key>
    <key name="key1">value</key>
  </section>
</configuration>

先前的設定檔會使用 value 載入下列機碼:The previous configuration file loads the following keys with value:

  • section:section0:key:key0section:section0:key:key0
  • section:section0:key:key1section:section0:key:key1
  • section:section1:key:key0section:section1:key:key0
  • section:section1:key:key1section:section1:key:key1

屬性可用來提供值:Attributes can be used to supply values:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <key attribute="value" />
  <section>
    <key attribute="value" />
  </section>
</configuration>

先前的設定檔會使用 value 載入下列機碼:The previous configuration file loads the following keys with value:

  • key:attributekey:attribute
  • section:key:attributesection:key:attribute

每個檔案機碼設定提供者Key-per-file Configuration Provider

KeyPerFileConfigurationProvider 使用目錄的檔案做為設定機碼值組。The KeyPerFileConfigurationProvider uses a directory's files as configuration key-value pairs. 機碼是檔案名稱。The key is the file name. 值包含檔案的內容。The value contains the file's contents. 每個檔案機碼設定提供者是在 Docker 主機案例中使用。The Key-per-file Configuration Provider is used in Docker hosting scenarios.

若要啟用每個檔案機碼設定,請在 ConfigurationBuilder 的執行個體上呼叫 AddKeyPerFile 延伸模組方法。To activate key-per-file configuration, call the AddKeyPerFile extension method on an instance of ConfigurationBuilder. 檔案的 directoryPath 必須是絕對路徑。The directoryPath to the files must be an absolute path.

多載允許指定:Overloads permit specifying:

  • 設定來源的 Action<KeyPerFileConfigurationSource> 委派。An Action<KeyPerFileConfigurationSource> delegate that configures the source.
  • 目錄是否為選擇性與目錄的路徑。Whether the directory is optional and the path to the directory.

雙底線 (__) 是做為檔案名稱中的設定金鑰分隔符號使用。The double-underscore (__) is used as a configuration key delimiter in file names. 例如,檔案名稱 Logging__LogLevel__System 會產生設定金鑰 Logging:LogLevel:SystemFor example, the file name Logging__LogLevel__System produces the configuration key Logging:LogLevel:System.

建置主機時呼叫 ConfigureAppConfiguration 以指定應用程式的設定:Call ConfigureAppConfiguration when building the host to specify the app's configuration:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.SetBasePath(Directory.GetCurrentDirectory());
    var path = Path.Combine(
        Directory.GetCurrentDirectory(), "path/to/files");
    config.AddKeyPerFile(directoryPath: path, optional: true);
})

透過 SetBasePath 設定基底路徑。The base path is set with SetBasePath.

記憶體設定提供者Memory Configuration Provider

MemoryConfigurationProvider 使用記憶體內集合做為設定機碼值組。The MemoryConfigurationProvider uses an in-memory collection as configuration key-value pairs.

若要啟用記憶體內集合設定,請在 ConfigurationBuilder 的執行個體上呼叫 AddInMemoryCollection 延伸模組方法。To activate in-memory collection configuration, call the AddInMemoryCollection extension method on an instance of ConfigurationBuilder.

設定提供者可以使用 IEnumerable<KeyValuePair<String,String>> 來初始化。The configuration provider can be initialized with an IEnumerable<KeyValuePair<String,String>>.

建置主機時呼叫 ConfigureAppConfiguration 以指定應用程式的設定。Call ConfigureAppConfiguration when building the host to specify the app's configuration.

下列範例會建立組態字典:In the following example, a configuration dictionary is created:

public static readonly Dictionary<string, string> _dict = 
    new Dictionary<string, string>
    {
        {"MemoryCollectionKey1", "value1"},
        {"MemoryCollectionKey2", "value2"}
    };

字典會與 AddInMemoryCollection 的呼叫搭配使用以提供組態:The dictionary is used with a call to AddInMemoryCollection to provide the configuration:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddInMemoryCollection(_dict);
})

GetValueGetValue

ConfigurationBinder.GetValue<T> 會從具有所指定機碼的組態擷取值,並將其轉換為指定的型別。ConfigurationBinder.GetValue<T> extracts a value from configuration with a specified key and converts it to the specified type. 若找不到機碼,多載允許您提供預設值。An overload permits you to provide a default value if the key isn't found.

下列範例:The following example:

  • 從具有機碼 NumberKey 的組態擷取字串值。Extracts the string value from configuration with the key NumberKey. 若在組態機碼中找不到 NumberKey,則會使用預設值 99If NumberKey isn't found in the configuration keys, the default value of 99 is used.
  • 鍵入值為 intTypes the value as an int.
  • NumberConfig 屬性中儲存值供頁面使用。Stores the value in the NumberConfig property for use by the page.
public class IndexModel : PageModel
{
    public IndexModel(IConfiguration config)
    {
        _config = config;
    }

    public int NumberConfig { get; private set; }

    public void OnGet()
    {
        NumberConfig = _config.GetValue<int>("NumberKey", 99);
    }
}

GetSection、GetChildren 與 ExistsGetSection, GetChildren, and Exists

針對下面的範例,請考慮下列 JSON 檔案。For the examples that follow, consider the following JSON file. 在兩個區段中找到四個機碼,其中一個包括子區段組:Four keys are found across two sections, one of which includes a pair of subsections:

{
  "section0": {
    "key0": "value",
    "key1": "value"
  },
  "section1": {
    "key0": "value",
    "key1": "value"
  },
  "section2": {
    "subsection0" : {
      "key0": "value",
      "key1": "value"
    },
    "subsection1" : {
      "key0": "value",
      "key1": "value"
    }
  }
}

當檔案被讀入到設定之後,會建立下列唯一階層式機碼以存放設定值:When the file is read into configuration, the following unique hierarchical keys are created to hold the configuration values:

  • section0:key0section0:key0
  • section0:key1section0:key1
  • section1:key0section1:key0
  • section1:key1section1:key1
  • section2:subsection0:key0section2:subsection0:key0
  • section2:subsection0:key1section2:subsection0:key1
  • section2:subsection1:key0section2:subsection1:key0
  • section2:subsection1:key1section2:subsection1:key1

GetSectionGetSection

IConfiguration.GetSection 會擷取具有所指定子區段機碼的設定子區段。IConfiguration.GetSection extracts a configuration subsection with the specified subsection key.

若要傳回 section1 中只包含一個機碼值組的 IConfigurationSection,請呼叫 GetSection 並提供區段名稱:To return an IConfigurationSection containing only the key-value pairs in section1, call GetSection and supply the section name:

var configSection = _config.GetSection("section1");

configSection 沒有值,只有索引鍵和路徑。The configSection doesn't have a value, only a key and a path.

同樣地,若要取得 section2:subsection0 中之機碼的值,請呼叫 GetSection 並提供區段路徑:Similarly, to obtain the values for keys in section2:subsection0, call GetSection and supply the section path:

var configSection = _config.GetSection("section2:subsection0");

GetSection 絕不會傳回 nullGetSection never returns null. 若找不到相符的區段,會傳回空的 IConfigurationSectionIf a matching section isn't found, an empty IConfigurationSection is returned.

GetSection 傳回相符區段時,未填入 ValueWhen GetSection returns a matching section, Value isn't populated. 當區段存在時,會傳回 KeyPathA Key and Path are returned when the section exists.

GetChildrenGetChildren

section2 上之 IConfiguration.GetChildren 的呼叫會取得包括下列項目的 IEnumerable<IConfigurationSection>A call to IConfiguration.GetChildren on section2 obtains an IEnumerable<IConfigurationSection> that includes:

  • subsection0
  • subsection1
var configSection = _config.GetSection("section2");

var children = configSection.GetChildren();

存在Exists

使用 ConfigurationExtensions.Exists 來判斷設定區段是否存在:Use ConfigurationExtensions.Exists to determine if a configuration section exists:

var sectionExists = _config.GetSection("section2:subsection2").Exists();

以範例資料為例, sectionExistsfalse,因未設定資料中沒有 section2:subsection2 區段。Given the example data, sectionExists is false because there isn't a section2:subsection2 section in the configuration data.

繫結到類別Bind to a class

設定可以繫結到類別,以使用選項模式代表相關設定的群組。Configuration can be bound to classes that represent groups of related settings using the options pattern. 如需詳細資訊,請參閱 ASP.NET Core 中的選項模式For more information, see ASP.NET Core 中的選項模式.

設定值是以字串傳回,但是呼叫 Bind 會啟用 POCO 物件的建構。Configuration values are returned as strings, but calling Bind enables the construction of POCO objects.

範例應用程式包含 Starship 模型 (Models/Starship.cs):The sample app contains a Starship model (Models/Starship.cs):

public class Starship
{
    public string Name { get; set; }
    public string Registry { get; set; }
    public string Class { get; set; }
    public decimal Length { get; set; }
    public bool Commissioned { get; set; }
}
public class Starship
{
    public string Name { get; set; }
    public string Registry { get; set; }
    public string Class { get; set; }
    public decimal Length { get; set; }
    public bool Commissioned { get; set; }
}

當範例應用程式使用 JSON 設定提供者來載入設定時,starship.json 檔案的 starship 區段會建立設定:The starship section of the starship.json file creates the configuration when the sample app uses the JSON Configuration Provider to load the configuration:

{
  "starship": {
    "name": "USS Enterprise",
    "registry": "NCC-1701",
    "class": "Constitution",
    "length": 304.8,
    "commissioned": false
  },
  "trademark": "Paramount Pictures Corp. http://www.paramount.com"
}
{
  "starship": {
    "name": "USS Enterprise",
    "registry": "NCC-1701",
    "class": "Constitution",
    "length": 304.8,
    "commissioned": false
  },
  "trademark": "Paramount Pictures Corp. http://www.paramount.com"
}

會建立下列設定機碼值組:The following configuration key-value pairs are created:

KeyKey Value
starship:namestarship:name USS EnterpriseUSS Enterprise
starship:registrystarship:registry NCC-1701NCC-1701
starship:classstarship:class ConstitutionConstitution
starship:lengthstarship:length 304.8304.8
starship:commissionedstarship:commissioned FalseFalse
trademarktrademark Paramount Pictures Corp. https://www.paramount.comParamount Pictures Corp. https://www.paramount.com

範例應用程式使用 starship 機碼呼叫 GetSectionThe sample app calls GetSection with the starship key. starship 機碼值組會被隔離。The starship key-value pairs are isolated. 會在子區段上呼叫 Bind 方法,並傳入 Starship 類別的執行個體。The Bind method is called on the subsection passing in an instance of the Starship class. 繫結執行個體值之後,執行個體會被指派給屬性以用於轉譯:After binding the instance values, the instance is assigned to a property for rendering:

var starship = new Starship();
_config.GetSection("starship").Bind(starship);
Starship = starship;
var starship = new Starship();
_config.GetSection("starship").Bind(starship);
Starship = starship;

繫結至物件圖形Bind to an object graph

Bind 可以繫結整個 POCO 物件圖形。Bind is capable of binding an entire POCO object graph.

範例包含 TvShow 模型,其物件圖形包括 MetadataActors 類別 (Models/TvShow.cs):The sample contains a TvShow model whose object graph includes Metadata and Actors classes (Models/TvShow.cs):

public class TvShow
{
    public Metadata Metadata { get; set; }
    public Actors Actors { get; set; }
    public string Legal { get; set; }
}

public class Metadata
{
    public string Series { get; set; }
    public string Title { get; set; }
    public DateTime AirDate { get; set; }
    public int Episodes { get; set; }
}

public class Actors
{
    public string Names { get; set; }
}
public class TvShow
{
    public Metadata Metadata { get; set; }
    public Actors Actors { get; set; }
    public string Legal { get; set; }
}

public class Metadata
{
    public string Series { get; set; }
    public string Title { get; set; }
    public DateTime AirDate { get; set; }
    public int Episodes { get; set; }
}

public class Actors
{
    public string Names { get; set; }
}

範例應用程式有 tvshow.xml 檔案,其中包含設定資料:The sample app has a tvshow.xml file containing the configuration data:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <tvshow>
    <metadata>
      <series>Dr. Who</series>
      <title>The Sun Makers</title>
      <airdate>11/26/1977</airdate>
      <episodes>4</episodes>
    </metadata>
    <actors>
      <names>Tom Baker, Louise Jameson, John Leeson</names>
    </actors>
    <legal>(c)1977 BBC https://www.bbc.co.uk/programmes/b006q2x0</legal>
  </tvshow>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <tvshow>
    <metadata>
      <series>Dr. Who</series>
      <title>The Sun Makers</title>
      <airdate>11/26/1977</airdate>
      <episodes>4</episodes>
    </metadata>
    <actors>
      <names>Tom Baker, Louise Jameson, John Leeson</names>
    </actors>
    <legal>(c)1977 BBC https://www.bbc.co.uk/programmes/b006q2x0</legal>
  </tvshow>
</configuration>

設定會被繫結到整個 TvShow 物件 (使用 Bind 方法)。Configuration is bound to the entire TvShow object graph with the Bind method. 已繫結的執行個體會被指派給屬性以用於轉譯:The bound instance is assigned to a property for rendering:

var tvShow = new TvShow();
_config.GetSection("tvshow").Bind(tvShow);
TvShow = tvShow;

ConfigurationBinder.Get<T> 會繫結並傳回所指定型別。ConfigurationBinder.Get<T> binds and returns the specified type. Get<T> 比使用 Bind 更方便。Get<T> is more convenient than using Bind. 下列程式碼顯示如何根據上面的範例使用 Get<T>,這可讓您直接將已繫結的執行個體指派給屬性以用於轉譯:The following code shows how to use Get<T> with the preceding example, which allows the bound instance to be directly assigned to the property used for rendering:

TvShow = _config.GetSection("tvshow").Get<TvShow>();
TvShow = _config.GetSection("tvshow").Get<TvShow>();

將陣列繫結到類別Bind an array to a class

範例應用程式示範此節中解釋的概念。 The sample app demonstrates the concepts explained in this section.

Bind 支援在設定機碼中使用陣列索引將陣列繫結到物件。The Bind supports binding arrays to objects using array indices in configuration keys. 任何公開數值機碼區段 (:0::1:、… :{n}:) 的陣列格式都能繫結到POCO 類別陣列。Any array format that exposes a numeric key segment (:0:, :1:, … :{n}:) is capable of array binding to a POCO class array.

注意

繫結是由慣例提供。Binding is provided by convention. 自訂設定提供者不需要實作陣列繫結。Custom configuration providers aren't required to implement array binding.

記憶體內陣列處理In-memory array processing

考慮下表中顯示的設定機碼與值。Consider the configuration keys and values shown in the following table.

KeyKey Value
array:entries:0array:entries:0 value0value0
array:entries:1array:entries:1 value1value1
array:entries:2array:entries:2 value2value2
array:entries:4array:entries:4 value4value4
array:entries:5array:entries:5 value5value5

這些機碼與值是使用「記憶體設定提供者」在範例應用程式中載入:These keys and values are loaded in the sample app using the Memory Configuration Provider:

public class Program
{
    public static Dictionary<string, string> arrayDict = 
        new Dictionary<string, string>
        {
            {"array:entries:0", "value0"},
            {"array:entries:1", "value1"},
            {"array:entries:2", "value2"},
            {"array:entries:4", "value4"},
            {"array:entries:5", "value5"}
        };

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddInMemoryCollection(arrayDict);
                config.AddJsonFile(
                    "json_array.json", optional: false, reloadOnChange: false);
                config.AddJsonFile(
                    "starship.json", optional: false, reloadOnChange: false);
                config.AddXmlFile(
                    "tvshow.xml", optional: false, reloadOnChange: false);
                config.AddEFConfiguration(
                    options => options.UseInMemoryDatabase("InMemoryDb"));
                config.AddCommandLine(args);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
public class Program
{
    public static Dictionary<string, string> arrayDict = 
        new Dictionary<string, string>
        {
            {"array:entries:0", "value0"},
            {"array:entries:1", "value1"},
            {"array:entries:2", "value2"},
            {"array:entries:4", "value4"},
            {"array:entries:5", "value5"}
        };

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddInMemoryCollection(arrayDict);
                config.AddJsonFile(
                    "json_array.json", optional: false, reloadOnChange: false);
                config.AddJsonFile(
                    "starship.json", optional: false, reloadOnChange: false);
                config.AddXmlFile(
                    "tvshow.xml", optional: false, reloadOnChange: false);
                config.AddEFConfiguration(
                    options => options.UseInMemoryDatabase("InMemoryDb"));
                config.AddCommandLine(args);
            })
            .UseStartup<Startup>();
}

陣列會跳過索引 #3 的值。The array skips a value for index #3. 設定繫結程式無法繫結 Null 值或在已繫結的物件中建立 Null 項目,這在示範繫結此陣列的結果到某物件的時候已經很清楚。The configuration binder isn't capable of binding null values or creating null entries in bound objects, which becomes clear in a moment when the result of binding this array to an object is demonstrated.

在範例應用程式中,POCO 類別可用來存放繫結設定資料:In the sample app, a POCO class is available to hold the bound configuration data:

public class ArrayExample
{
    public string[] Entries { get; set; }
}
public class ArrayExample
{
    public string[] Entries { get; set; }
}

設定資料已繫結到物件:The configuration data is bound to the object:

var arrayExample = new ArrayExample();
_config.GetSection("array").Bind(arrayExample);

也可以使用 ConfigurationBinder.Get<T> 語法,其會產生更精簡的程式碼:ConfigurationBinder.Get<T> syntax can also be used, which results in more compact code:

ArrayExample = _config.GetSection("array").Get<ArrayExample>();
ArrayExample = _config.GetSection("array").Get<ArrayExample>();

繫結物件 (ArrayExample的執行個體) 會從設定接收陣列資料。The bound object, an instance of ArrayExample, receives the array data from configuration.

ArrayExample.Entries 索引ArrayExample.Entries Index ArrayExample.EntriesArrayExample.Entries Value
00 value0value0
11 value1value1
22 value2value2
33 value4value4
44 value5value5

繫結物件中的索引 #3 存放 array:4 設定機碼與其 value4 的設定資料。Index #3 in the bound object holds the configuration data for the array:4 configuration key and its value of value4. 當繫結包含陣列的設定資料時,設定機碼中的陣列索引只會用來列舉設定資料 (當建立物件時)。When configuration data containing an array is bound, the array indices in the configuration keys are merely used to iterate the configuration data when creating the object. 設定資料中不能保留 Null 值,當設定機碼中的陣列略過一或多個索引時,不會在繫結物件中建立 Null 值項目。A null value can't be retained in configuration data, and a null-valued entry isn't created in a bound object when an array in configuration keys skip one or more indices.

由會在設定中產生正確機碼值組的任何設定提供者繫結到 ArrayExample 執行個體之前,可以提供索引 #3 缺少的設定項目。The missing configuration item for index #3 can be supplied before binding to the ArrayExample instance by any configuration provider that produces the correct key-value pair in configuration. 若範例包含具有缺少之機碼值組的額外 JSON 設定提供者,ArrayExample.Entries 會符合完整的設定陣列:If the sample included an additional JSON Configuration Provider with the missing key-value pair, the ArrayExample.Entries matches the complete configuration array:

missing_value.jsonmissing_value.json:

{
  "array:entries:3": "value3"
}

ConfigureAppConfiguration中:In ConfigureAppConfiguration:

config.AddJsonFile(
    "missing_value.json", optional: false, reloadOnChange: false);

表格中顯示的機碼值組會載入到設定中。The key-value pair shown in the table is loaded into configuration.

KeyKey Value
array:entries:3array:entries:3 value3value3

在「JSON 設定提供者」包含索引 #3 的項目之後,若繫結 ArrayExample 類別執行個體,ArrayExample.Entries 陣列會包括這些值:If the ArrayExample class instance is bound after the JSON Configuration Provider includes the entry for index #3, the ArrayExample.Entries array includes the value.

ArrayExample.Entries 索引ArrayExample.Entries Index ArrayExample.EntriesArrayExample.Entries Value
00 value0value0
11 value1value1
22 value2value2
33 value3value3
44 value4value4
55 value5value5

JSON 陣列處理JSON array processing

若 JSON 檔案包含陣列,會為具有以零為基礎之區段索引的陣列元素建立設定機碼。If a JSON file contains an array, configuration keys are created for the array elements with a zero-based section index. 在下列設定檔中,subsection 是陣列:In the following configuration file, subsection is an array:

{
  "json_array": {
    "key": "valueA",
    "subsection": [
      "valueB",
      "valueC",
      "valueD"
    ]
  }
}
{
  "json_array": {
    "key": "valueA",
    "subsection": [
      "valueB",
      "valueC",
      "valueD"
    ]
  }
}

「JSON 設定提供者」會將設定資料讀入到下列機碼值組:The JSON Configuration Provider reads the configuration data into the following key-value pairs:

KeyKey Value
json_array:keyjson_array:key valueAvalueA
json_array:subsection:0json_array:subsection:0 valueBvalueB
json_array:subsection:1json_array:subsection:1 valueCvalueC
json_array:subsection:2json_array:subsection:2 valueDvalueD

在範例應用程式中,下列 POCO 類別可用來繫結設定機碼值組:In the sample app, the following POCO class is available to bind the configuration key-value pairs:

public class JsonArrayExample
{
    public string Key { get; set; }
    public string[] Subsection { get; set; }
}
public class JsonArrayExample
{
    public string Key { get; set; }
    public string[] Subsection { get; set; }
}

在繫結之後,JsonArrayExample.Key 會存放值 valueAAfter binding, JsonArrayExample.Key holds the value valueA. 子區段值會存放在 POCO 陣列屬性 Subsection 中。The subsection values are stored in the POCO array property, Subsection.

JsonArrayExample.Subsection 索引JsonArrayExample.Subsection Index JsonArrayExample.SubsectionJsonArrayExample.Subsection Value
00 valueBvalueB
11 valueCvalueC
22 valueDvalueD

自訂設定提供者Custom configuration provider

範例應用程式示範如何建立會使用 Entity Framework (EF) 從資料庫讀取設定機碼值組的基本設定提供者。The sample app demonstrates how to create a basic configuration provider that reads configuration key-value pairs from a database using Entity Framework (EF).

提供者具有下列特性:The provider has the following characteristics:

  • EF 記憶體內資料庫會用於示範用途。The EF in-memory database is used for demonstration purposes. 若要使用需要連接字串的資料庫,請實作第二個 ConfigurationBuilder 以從另一個設定提供者提供連接字串。To use a database that requires a connection string, implement a secondary ConfigurationBuilder to supply the connection string from another configuration provider.
  • 啟動時,該提供者會將資料庫資料表讀入到設定中。The provider reads a database table into configuration at startup. 該提供者不會以個別機碼為基礎查詢資料庫。The provider doesn't query the database on a per-key basis.
  • 未實作變更時重新載入,因此在應用程式啟動後更新資料庫對應用程式設定沒有影響。Reload-on-change isn't implemented, so updating the database after the app starts has no effect on the app's configuration.

定義 EFConfigurationValue 實體來在資料庫中存放設定值。Define an EFConfigurationValue entity for storing configuration values in the database.

Models/EFConfigurationValue.csModels/EFConfigurationValue.cs:

public class EFConfigurationValue
{
    public string Id { get; set; }
    public string Value { get; set; }
}

新增 EFConfigurationContext 以存放及存取已設定的值。Add an EFConfigurationContext to store and access the configured values.

EFConfigurationProvider/EFConfigurationContext.csEFConfigurationProvider/EFConfigurationContext.cs:

public class EFConfigurationContext : DbContext
{
    public EFConfigurationContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<EFConfigurationValue> Values { get; set; }
}

建立會實作 IConfigurationSource 的類別。Create a class that implements IConfigurationSource.

EFConfigurationProvider/EFConfigurationSource.csEFConfigurationProvider/EFConfigurationSource.cs:

public class EFConfigurationSource : IConfigurationSource
{
    private readonly Action<DbContextOptionsBuilder> _optionsAction;

    public EFConfigurationSource(Action<DbContextOptionsBuilder> optionsAction)
    {
        _optionsAction = optionsAction;
    }

    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new EFConfigurationProvider(_optionsAction);
    }
}

透過繼承自 ConfigurationProvider 來建立自訂設定提供者。Create the custom configuration provider by inheriting from ConfigurationProvider. 若資料庫是空的,設定提供者會初始化資料庫。The configuration provider initializes the database when it's empty.

EFConfigurationProvider/EFConfigurationProvider.csEFConfigurationProvider/EFConfigurationProvider.cs:

public class EFConfigurationProvider : ConfigurationProvider
{
    public EFConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction)
    {
        OptionsAction = optionsAction;
    }

    Action<DbContextOptionsBuilder> OptionsAction { get; }

    // Load config data from EF DB.
    public override void Load()
    {
        var builder = new DbContextOptionsBuilder<EFConfigurationContext>();

        OptionsAction(builder);

        using (var dbContext = new EFConfigurationContext(builder.Options))
        {
            dbContext.Database.EnsureCreated();

            Data = !dbContext.Values.Any()
                ? CreateAndSaveDefaultValues(dbContext)
                : dbContext.Values.ToDictionary(c => c.Id, c => c.Value);
        }
    }

    private static IDictionary<string, string> CreateAndSaveDefaultValues(
        EFConfigurationContext dbContext)
    {
        // Quotes (c)2005 Universal Pictures: Serenity
        // https://www.uphe.com/movies/serenity
        var configValues = new Dictionary<string, string>
            {
                { "quote1", "I aim to misbehave." },
                { "quote2", "I swallowed a bug." },
                { "quote3", "You can't stop the signal, Mal." }
            };

        dbContext.Values.AddRange(configValues
            .Select(kvp => new EFConfigurationValue 
                {
                    Id = kvp.Key,
                    Value = kvp.Value
                })
            .ToArray());

        dbContext.SaveChanges();

        return configValues;
    }
}

AddEFConfiguration 擴充方法允許新增設定來源到 ConfigurationBuilderAn AddEFConfiguration extension method permits adding the configuration source to a ConfigurationBuilder.

Extensions/EntityFrameworkExtensions.cs:Extensions/EntityFrameworkExtensions.cs:

public static class EntityFrameworkExtensions
{
    public static IConfigurationBuilder AddEFConfiguration(
        this IConfigurationBuilder builder, 
        Action<DbContextOptionsBuilder> optionsAction)
    {
        return builder.Add(new EFConfigurationSource(optionsAction));
    }
}

下列程式碼顯示如何在 Program.cs 中使用自訂 EFConfigurationProviderThe following code shows how to use the custom EFConfigurationProvider in Program.cs:

public class Program
{
    public static Dictionary<string, string> arrayDict = 
        new Dictionary<string, string>
        {
            {"array:entries:0", "value0"},
            {"array:entries:1", "value1"},
            {"array:entries:2", "value2"},
            {"array:entries:4", "value4"},
            {"array:entries:5", "value5"}
        };

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddInMemoryCollection(arrayDict);
                config.AddJsonFile(
                    "json_array.json", optional: false, reloadOnChange: false);
                config.AddJsonFile(
                    "starship.json", optional: false, reloadOnChange: false);
                config.AddXmlFile(
                    "tvshow.xml", optional: false, reloadOnChange: false);
                config.AddEFConfiguration(
                    options => options.UseInMemoryDatabase("InMemoryDb"));
                config.AddCommandLine(args);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Models/EFConfigurationValue.csModels/EFConfigurationValue.cs:

public class EFConfigurationValue
{
    public string Id { get; set; }
    public string Value { get; set; }
}

新增 EFConfigurationContext 以存放及存取已設定的值。Add an EFConfigurationContext to store and access the configured values.

EFConfigurationProvider/EFConfigurationContext.csEFConfigurationProvider/EFConfigurationContext.cs:

public class EFConfigurationContext : DbContext
{
    public EFConfigurationContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<EFConfigurationValue> Values { get; set; }
}

建立會實作 IConfigurationSource 的類別。Create a class that implements IConfigurationSource.

EFConfigurationProvider/EFConfigurationSource.csEFConfigurationProvider/EFConfigurationSource.cs:

public class EFConfigurationSource : IConfigurationSource
{
    private readonly Action<DbContextOptionsBuilder> _optionsAction;

    public EFConfigurationSource(Action<DbContextOptionsBuilder> optionsAction)
    {
        _optionsAction = optionsAction;
    }

    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new EFConfigurationProvider(_optionsAction);
    }
}

透過繼承自 ConfigurationProvider 來建立自訂設定提供者。Create the custom configuration provider by inheriting from ConfigurationProvider. 若資料庫是空的,設定提供者會初始化資料庫。The configuration provider initializes the database when it's empty.

EFConfigurationProvider/EFConfigurationProvider.csEFConfigurationProvider/EFConfigurationProvider.cs:

public class EFConfigurationProvider : ConfigurationProvider
{
    public EFConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction)
    {
        OptionsAction = optionsAction;
    }

    Action<DbContextOptionsBuilder> OptionsAction { get; }

    // Load config data from EF DB.
    public override void Load()
    {
        var builder = new DbContextOptionsBuilder<EFConfigurationContext>();

        OptionsAction(builder);

        using (var dbContext = new EFConfigurationContext(builder.Options))
        {
            dbContext.Database.EnsureCreated();

            Data = !dbContext.Values.Any()
                ? CreateAndSaveDefaultValues(dbContext)
                : dbContext.Values.ToDictionary(c => c.Id, c => c.Value);
        }
    }

    private static IDictionary<string, string> CreateAndSaveDefaultValues(
        EFConfigurationContext dbContext)
    {
        // Quotes (c)2005 Universal Pictures: Serenity
        // https://www.uphe.com/movies/serenity
        var configValues = new Dictionary<string, string>
            {
                { "quote1", "I aim to misbehave." },
                { "quote2", "I swallowed a bug." },
                { "quote3", "You can't stop the signal, Mal." }
            };

        dbContext.Values.AddRange(configValues
            .Select(kvp => new EFConfigurationValue 
                {
                    Id = kvp.Key,
                    Value = kvp.Value
                })
            .ToArray());

        dbContext.SaveChanges();

        return configValues;
    }
}

AddEFConfiguration 擴充方法允許新增設定來源到 ConfigurationBuilderAn AddEFConfiguration extension method permits adding the configuration source to a ConfigurationBuilder.

Extensions/EntityFrameworkExtensions.cs:Extensions/EntityFrameworkExtensions.cs:

public static class EntityFrameworkExtensions
{
    public static IConfigurationBuilder AddEFConfiguration(
        this IConfigurationBuilder builder, 
        Action<DbContextOptionsBuilder> optionsAction)
    {
        return builder.Add(new EFConfigurationSource(optionsAction));
    }
}

下列程式碼顯示如何在 Program.cs 中使用自訂 EFConfigurationProviderThe following code shows how to use the custom EFConfigurationProvider in Program.cs:

public class Program
{
    public static Dictionary<string, string> arrayDict = 
        new Dictionary<string, string>
        {
            {"array:entries:0", "value0"},
            {"array:entries:1", "value1"},
            {"array:entries:2", "value2"},
            {"array:entries:4", "value4"},
            {"array:entries:5", "value5"}
        };

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddInMemoryCollection(arrayDict);
                config.AddJsonFile(
                    "json_array.json", optional: false, reloadOnChange: false);
                config.AddJsonFile(
                    "starship.json", optional: false, reloadOnChange: false);
                config.AddXmlFile(
                    "tvshow.xml", optional: false, reloadOnChange: false);
                config.AddEFConfiguration(
                    options => options.UseInMemoryDatabase("InMemoryDb"));
                config.AddCommandLine(args);
            })
            .UseStartup<Startup>();
}

在啟動期間存取組態Access configuration during startup

IConfiguration 插入到 Startup 建構函式,以存取 Startup.ConfigureServices 中的設定值。Inject IConfiguration into the Startup constructor to access configuration values in Startup.ConfigureServices. 若要存取 Startup.Configure 中的設定,請直接將 IConfiguration 插入到方法或從建構函式使用執行個體:To access configuration in Startup.Configure, either inject IConfiguration directly into the method or use the instance from the constructor:

public class Startup
{
    private readonly IConfiguration _config;

    public Startup(IConfiguration config)
    {
        _config = config;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var value = _config["key"];
    }

    public void Configure(IApplicationBuilder app, IConfiguration config)
    {
        var value = config["key"];
    }
}

如需使用啟動方便方法來存取設定的範例,請參閱應用程式啟動:便利的方法For an example of accessing configuration using startup convenience methods, see App startup: Convenience methods.

存取 Razor Pages 頁面或 MVC 檢視中的設定Access configuration in a Razor Pages page or MVC view

若要在 [Razor Pages 頁面] 頁面或 MVC 檢視中存取組態設定,請針對 Microsoft.Extensions.Configuration 命名空間 using 指示詞 (C# 參考:using 指示詞),並將 IConfiguration 插入到頁面或檢視中。To access configuration settings in a Razor Pages page or an MVC view, add a using directive (C# reference: using directive) for the Microsoft.Extensions.Configuration namespace and inject IConfiguration into the page or view.

在 [Razor 頁面] 頁面中:In a Razor Pages page:

@page
@model IndexModel
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Index Page</title>
</head>
<body>
    <h1>Access configuration in a Razor Pages page</h1>
    <p>Configuration value for 'key': @Configuration["key"]</p>
</body>
</html>

在 MVC 檢視中:In an MVC view:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Index View</title>
</head>
<body>
    <h1>Access configuration in an MVC view</h1>
    <p>Configuration value for 'key': @Configuration["key"]</p>
</body>
</html>

從外部組件新增設定Add configuration from an external assembly

IHostingStartup 實作允許在啟動時從應用程式 Startup 類別外部的外部組件,針對應用程式新增增強功能。An IHostingStartup implementation allows adding enhancements to an app at startup from an external assembly outside of the app's Startup class. 如需詳細資訊,請參閱 在 ASP.NET Core 中使用裝載啟動組件For more information, see 在 ASP.NET Core 中使用裝載啟動組件.

其他資源Additional resources