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
  • 命令列引數Command-line arguments
  • 自訂提供者 (已安裝或已建立)Custom providers (installed or created)
  • 目錄檔案Directory files
  • 環境變數Environment variables
  • 記憶體內部 .NET 物件In-memory .NET objects
  • 設定檔Settings files
  • Azure Key VaultAzure Key Vault
  • 命令列引數Command-line arguments
  • 自訂提供者 (已安裝或已建立)Custom providers (installed or created)
  • 環境變數Environment variables
  • 記憶體內部 .NET 物件In-memory .NET objects
  • 設定檔Settings files
  • 命令列引數Command-line arguments
  • 自訂提供者 (已安裝或已建立)Custom providers (installed or created)
  • 環境變數Environment variables
  • 記憶體內部 .NET 物件In-memory .NET objects
  • 設定檔Settings files

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

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

此主題中提供的範例需要:The examples provided in this topic rely upon:

這些套件均包含在 Microsoft.AspNetCore.App j5/ 中繼套件中。These three packages are included in the Microsoft.AspNetCore.App metapackage.

這三個套件都包含在 Microsoft.AspNetCore.All 中繼套件中。These three packages are included in the Microsoft.AspNetCore.All metapackage.

主機與應用程式設定的比較Host vs. 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 become part of the app's global 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 中代管.

安全性Security

採用下列最佳做法:Adopt the following best practices:

  • 永遠不要將密碼或其他敏感性資料儲存在設定提供者程式碼或純文字設定檔中。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.

深入了解如何使用多個環境使用祕密管理員管理開發中的應用程式祕密安全儲存體 (包括有關使用環境變數來存放敏感性資料的建議)。Learn more about how to use multiple environments and managing the safe storage of app secrets in development with the Secret Manager (includes advice on using environment variables to store sensitive data). 「祕密管理員」使用「檔案設定提供者」以 JSON 檔案在本機系統上存放使用者祕密。The Secret Manager uses the File Configuration Provider to store user secrets in a JSON file on the local system. 此主題稍後將說明「檔案設定提供者」。The File Configuration Provider is described later in this topic.

Azure Key Vault 是安全儲存應用程式祕密的一個選項。Azure Key Vault is one option for the safe storage of app secrets. 如需詳細資訊,請參閱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

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

「檔案設定提供者」可以在應用程式啟動之後且底層設定檔案變更時重新載入設定。File Configuration Providers have the ability to reload configuration when an underlying settings file is changed after app startup. 此主題稍後將說明「檔案設定提供者」。The File Configuration Provider is described later in this topic.

您可以在應用程式的相依性插入 (DI) 容器中找到 IConfigurationIConfiguration is available in the app's Dependency Injection (DI) container. 設定提供者無法使用 DI,因為當它們由主機設定時,它無法使用。Configuration providers can't utilize DI, as it's not available when they're set up by the host.

設定機碼會採用下列慣例: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 converted to 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.

設定值會採用下列慣例: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
命令列設定提供者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
提供者Provider 從…提供設定Provides configuration from…
Azure Key Vault 設定提供者 (安全性主題)Azure Key Vault Configuration Provider (Security topics) Azure Key VaultAzure Key Vault
命令列設定提供者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)
記憶體設定提供者Memory Configuration Provider 記憶體內集合In-memory collections
使用者祕密 (祕密管理員) (安全性主題)User secrets (Secret Manager) (Security topics) 使用者設定檔目錄中的檔案File in the user profile directory
提供者Provider 從…提供設定Provides configuration from…
命令列設定提供者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)
記憶體設定提供者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. 使用者祕密 (祕密管理員) (僅限開發環境)User secrets (Secret Manager) (in the Development environment only)
  3. 環境變數Environment variables
  4. 命令列引數Command-line arguments

將命令列設定提供者放在提供者序列結尾是常見作法,因為這樣可以讓命令列引數覆寫由其它提供者所設定的設定。It's a common practice 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初始化新的 WebHostBuilder 時,就會有這個提供者順序。This sequence of providers is put into place when you initialize a new WebHostBuilder with CreateDefaultBuilder. 如需詳細資訊,請參閱 Web主機:設定主機For more information, see Web Host: Set up a host.

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

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

ASP.NET Core 2.1 或更新版本中提供了 ConfigureAppConfiguration ConfigureAppConfiguration is available in ASP.NET Core 2.1 or later.

您可以使用 ConfigurationBuilder 並在 Startup Build 方法,以為應用程式 (而非主機) 建立提供者順序:This sequence of providers can be created for the app (not the host) with a ConfigurationBuilder and a call to its Build method in Startup:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, 
            reloadOnChange: true);

    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));

    if (appAssembly != null)
    {
        builder.AddUserSecrets(appAssembly, optional: true);
    }

    builder.AddEnvironmentVariables();

    Configuration = builder.Build();
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IConfiguration>(Configuration);
}

在上面的範例中,環境名稱 (env.EnvironmentName) 與應用程式組件名稱 (env.ApplicationName) 是由 IHostingEnvironment 提供。In the preceding example, the environment name (env.EnvironmentName) and app assembly name (env.ApplicationName) are provided by the IHostingEnvironment. 如需詳細資訊,請參閱在 ASP.NET Core 中使用多個環境For more information, see 在 ASP.NET Core 中使用多個環境.

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

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

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

當您使用 CreateDefaultBuilder 初始化新的 WebHostBuilder 時,會自動呼叫 AddCommandLineAddCommandLine is automatically called when you initialize a new WebHostBuilder with CreateDefaultBuilder. 如需詳細資訊,請參閱 Web主機:設定主機For more information, see Web Host: Set up a host.

CreateDefaultBuilder 也會載入:CreateDefaultBuilder also loads:

  • appsettings.jsonappsettings.<Environment>.json 載入其他選擇性設定。Optional configuration from appsettings.json and appsettings.<Environment>.json.
  • 使用者祕密 (祕密管理員) (在開發環境中)。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.

手動建置主機而且未呼叫 CreateDefaultBuilder 時,請呼叫 ConfigurationBuilder 執行個體的 AddCommandLine 延伸模組方法:When building the host manually and not calling CreateDefaultBuilder, call the AddCommandLine extension method on an instance of ConfigurationBuilder:

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

最後才呼叫提供者,以允許在執行階段傳遞的命令列引數覆寫由其他設定提供者所設定的設定。Call the provider last to allow the command-line arguments passed at runtime to override configuration set by other configuration providers.

使用 UseConfiguration 方法將設定套用到 WebHostBuilderApply the configuration to WebHostBuilder with the UseConfiguration method:

var config = new ConfigurationBuilder()
    .AddCommandLine(args)
    .Build();

var host = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .UseStartup<Startup>();

範例Example

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

1.x 範例應用程式會呼叫 ConfigurationBuilder 上的 AddCommandLineThe 1.x sample app calls AddCommandLine on a ConfigurationBuilder.

  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=),值可以是 Null。The value can be null 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=value --CommandLineKey2=value /CommandLineKey2=value
dotnet run --CommandLineKey1 value /CommandLineKey2 value
dotnet run CommandLineKey1= CommandLineKey2=value

切換對應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.
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var switchMappings = new Dictionary<string, string>
            {
                { "-CLKey1", "CommandLineKey1" },
                { "-CLKey2", "CommandLineKey2" }
            };

        var config = new ConfigurationBuilder()
            .AddCommandLine(args, switchMappings)
            .Build();

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

如上面的範例所示,當使用切換對應時,對 CreateDefaultBuilder 的呼叫不應該傳遞引數。As shown in the preceding example, the call to CreateDefaultBuilder shouldn't pass arguments when switch mappings are used. CreateDefaultBuilder 方法的 AddCommandLine 呼叫不包括對應的切換,而且沒有任何方式可以將切換對應字典傳遞給 CreateDefaultBuilderCreateDefaultBuilder method's AddCommandLine call doesn't include mapped switches, and there's no way to pass the switch mapping dictionary to CreateDefaultBuilder. 若對應切換中包含引數且已傳遞給 CreateDefaultBuilder,其 AddCommandLine 提供者會無法使用 FormatException 來初始化。If the arguments include a mapped switch and are passed to CreateDefaultBuilder, its AddCommandLine provider fails to initialize with a FormatException. 解決方式是不要傳遞引數給 CreateDefaultBuilder,而是允許 ConfigurationBuilder 方法的 AddCommandLine 方法同時處理引數與切換對應字典。The solution is not 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.

public static void Main(string[] args)
{
    var switchMappings = new Dictionary<string, string>
        {
            { "-CLKey1", "CommandLineKey1" },
            { "-CLKey2", "CommandLineKey2" }
        };

    var config = new ConfigurationBuilder()
        .AddCommandLine(args, switchMappings)
        .Build();

    var host = new WebHostBuilder()
        .UseConfiguration(config)
        .UseKestrel()
        .UseStartup<Startup>()
        .Start();

    using (host)
    {
        Console.ReadLine();
    }
}

建立切換對應字典之後,它會包含下表中所示的資料。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.

在環境變數中搭配階層式機碼使用時,冒號分隔字元 (:) 可能無法在所有平台上運作。When working with hierarchical keys in environment variables, a colon separator (:) may not work on all platforms. 所有平台都支援雙底線 (__),而且它會被冒號取代。A double underscore (__) is supported by all platforms and is 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 初始化新的 WebHostBuilder 時,會自動呼叫 AddEnvironmentVariablesAddEnvironmentVariables is automatically called when you initialize a new WebHostBuilder with CreateDefaultBuilder. 如需詳細資訊,請參閱 Web主機:設定主機For more information, see Web Host: Set up a host.

CreateDefaultBuilder 也會載入:CreateDefaultBuilder also loads:

  • appsettings.jsonappsettings.<Environment>.json 載入其他選擇性設定。Optional configuration from appsettings.json and appsettings.<Environment>.json.
  • 使用者祕密 (祕密管理員) (在開發環境中)。User secrets (Secret Manager) (in the Development environment).
  • 命令列引數。Command-line arguments.

從使用者祕密與 appsettings 檔案建立設定之後,會呼叫「環境變數設定提供者」。The Environment Variable 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.

您也可以直接呼叫 ConfigurationBuilder 執行個體上的 AddEnvironmentVariables 延伸模組方法:You can also directly call the AddEnvironmentVariables extension method on an instance of ConfigurationBuilder:

使用 UseConfiguration 方法將設定套用到 WebHostBuilderApply the configuration to WebHostBuilder with the UseConfiguration method:

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

var host = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .UseStartup<Startup>();

範例Example

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

1.x 範例應用程式會呼叫 ConfigurationBuilder 上的 AddEnvironmentVariablesThe 1.x sample app calls AddEnvironmentVariables on a ConfigurationBuilder.

  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 to those that start with the following:

  • ASPNETCORE_ASPNETCORE_
  • urlsurls
  • 記錄Logging
  • 環境ENVIRONMENT
  • contentRootcontentRoot
  • AllowedHostsAllowedHosts
  • applicationNameapplicationName
  • CommandLineCommandLine

若想要將所有環境變數公開給應用程式使用,請將 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:

若想要將所有環境變數公開給應用程式使用,請將 Controllers/HomeController.cs 中的 FilteredConfiguration 變更為下面這樣:If you wish to expose all of the environment variables available to the app, change the FilteredConfiguration in Controllers/HomeController.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.

靜態方便方法 CreateDefaultBuilder 會建立 WebHostBuilder 以建立應用程式的主機。The static convenience method CreateDefaultBuilder creates a WebHostBuilder to establish the app's host. WebHostBuilder 建立時,它會在前置詞為 ASPNETCORE_ 的環境變數中尋找其主機設定。When WebHostBuilder is created, it finds its host configuration in environment variables prefixed with ASPNETCORE_.

連接字串前置詞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.

呼叫 CreateDefaultBuilder 時,請使用下列設定呼叫 UseConfigurationWhen calling CreateDefaultBuilder, call UseConfiguration with the configuration:

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddIniFile("config.ini", optional: true, reloadOnChange: true)
            .Build();

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

建立 WebHostBuilder 目錄時,請使用下列設定呼叫 UseConfigurationWhen creating a WebHostBuilder directly, call UseConfiguration with the configuration:

使用 UseConfiguration 方法將設定套用到 WebHostBuilderApply the configuration to WebHostBuilder with the UseConfiguration method:

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddIniFile("config.ini", optional: true, reloadOnChange: true)
    .Build();

var host = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .UseStartup<Startup>();

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 初始化新的 WebHostBuilder 時,會自動呼叫 AddJsonFile 兩次。AddJsonFile is automatically called twice when you initialize a new WebHostBuilder 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.

如需詳細資訊,請參閱 Web主機:設定主機For more information, see Web Host: Set up a host.

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.

您也可以直接呼叫 ConfigurationBuilder 執行個體上的 AddJsonFile 延伸模組方法。You can also directly call the AddJsonFile extension method on an instance of ConfigurationBuilder.

呼叫 CreateDefaultBuilder 時,請使用下列設定呼叫 UseConfigurationWhen calling CreateDefaultBuilder, call UseConfiguration with the configuration:

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json", optional: true, reloadOnChange: true)
            .Build();

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

建立 WebHostBuilder 目錄時,請使用下列設定呼叫 UseConfigurationWhen creating a WebHostBuilder directly, call UseConfiguration with the configuration:

使用 UseConfiguration 方法將設定套用到 WebHostBuilderApply the configuration to WebHostBuilder with the UseConfiguration method:

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("config.json", optional: true, reloadOnChange: true)
    .Build();

var host = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .UseStartup<Startup>();

範例Example

2.x 範例應用程式可發揮靜態方便方法 CreateDefaultBuilder 的優勢以建置主機,這包括對 AddJsonFile 的兩次呼叫。The 2.x 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.x 範例應用程式會呼叫 ConfigurationBuilder 上的 AddJsonFile 兩次。The 1.x sample app calls AddJsonFile twice on a ConfigurationBuilder. 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.

呼叫 CreateDefaultBuilder 時,請使用下列設定呼叫 UseConfigurationWhen calling CreateDefaultBuilder, call UseConfiguration with the configuration:

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddXmlFile("config.xml", optional: true, reloadOnChange: true)
            .Build();

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

建立 WebHostBuilder 目錄時,請使用下列設定呼叫 UseConfigurationWhen creating a WebHostBuilder directly, call UseConfiguration with the configuration:

使用 UseConfiguration 方法將設定套用到 WebHostBuilderApply the configuration to WebHostBuilder with the UseConfiguration method:

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddXmlFile("config.xml", optional: true, reloadOnChange: true)
    .Build();

var host = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .UseStartup<Startup>();

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.

呼叫 CreateDefaultBuilder 時,請使用下列設定呼叫 UseConfigurationWhen calling CreateDefaultBuilder, call UseConfiguration with the configuration:

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files");
        var config = new ConfigurationBuilder()
            .AddKeyPerFile(directoryPath: path, optional: true)
            .Build();

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

建立 WebHostBuilder 目錄時,請使用下列設定呼叫 UseConfigurationWhen creating a WebHostBuilder directly, call UseConfiguration with the configuration:

var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files");
var config = new ConfigurationBuilder()
    .AddKeyPerFile(directoryPath: path, optional: true)
    .Build();

var host = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .UseStartup<Startup>();

記憶體設定提供者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>>.

呼叫 CreateDefaultBuilder 時,請使用下列設定呼叫 UseConfigurationWhen calling CreateDefaultBuilder, call UseConfiguration with the configuration:

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

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

建立 WebHostBuilder 目錄時,請使用下列設定呼叫 UseConfigurationWhen creating a WebHostBuilder directly, call UseConfiguration with the configuration:

使用 UseConfiguration 方法將設定套用到 WebHostBuilderApply the configuration to WebHostBuilder with the UseConfiguration method:

var dict = new Dictionary<string, string>
    {
        {"MemoryCollectionKey1", "value1"},
        {"MemoryCollectionKey2", "value2"}
    };

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

var host = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .UseStartup<Startup>();

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.

下列範例會從具有機碼 NumberKey 的設定擷取字串值、將值的型別設定為 int,並將值存放在變數 intValue 中。The following example extracts the string value from configuration with the key NumberKey, types the value as an int, and stores the value in the variable intValue. 若在設定機碼中找不到 NumberKeyintValue 會接收 99 的預設值:If NumberKey isn't found in the configuration keys, intValue receives the default value of 99:

var intValue = 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");

同樣地,若要取得 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.

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. http://www.paramount.comParamount Pictures Corp. http://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);
viewModel.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;
var tvShow = new TvShow();
_config.GetSection("tvshow").Bind(tvShow);
viewModel.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>();
viewModel.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:0array:0 value0value0
array:1array:1 value1value1
array:2array:2 value2value2
array:4array:4 value4value4
array:5array: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)
    {
        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>();
}
public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var 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"}
        };

        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddInMemoryCollection(arrayDict)
            .AddJsonFile("json_array.json", optional: false, reloadOnChange: false)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, 
                reloadOnChange: true)
            .AddEnvironmentVariables()
            .AddJsonFile("starship.json", optional: false, reloadOnChange: false)
            .AddXmlFile("tvshow.xml", optional: false, reloadOnChange: false)
            .AddEFConfiguration(options => options.UseInMemoryDatabase("InMemoryDb"))
            .AddCommandLine(Program.Args);

        Configuration = builder.Build();
    }

陣列會跳過索引 #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>();
viewModel.ArrayExample = _config.GetSection("array").Get<ArrayExample>();

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

ArrayExamples.Entries 索引ArrayExamples.Entries Index ArrayExamples.EntriesArrayExamples.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.

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

Startup 建構函式中:In the Startup constructor:

.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 的項目之後,若繫結 ArrayExamples 類別執行個體,ArrayExamples.Entries 陣列會包括這些值:If the ArrayExamples class instance is bound after the JSON Configuration Provider includes the entry for index #3, the ArrayExamples.Entries array includes the value.

ArrayExamples.Entries 索引ArrayExamples.Entries Index ArrayExamples.EntriesArrayExamples.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; }
}
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; }
}
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);
    }
}
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;
    }
}
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));
    }
}
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>();
}
public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var 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"}
        };

        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddInMemoryCollection(arrayDict)
            .AddJsonFile("json_array.json", optional: false, reloadOnChange: false)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, 
                reloadOnChange: true)
            .AddEnvironmentVariables()
            .AddJsonFile("starship.json", optional: false, reloadOnChange: false)
            .AddXmlFile("tvshow.xml", optional: false, reloadOnChange: false)
            .AddEFConfiguration(options => options.UseInMemoryDatabase("InMemoryDb"))
            .AddCommandLine(Program.Args);

        Configuration = builder.Build();
    }

在啟動期間存取組態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 中使用 IHostingStartup 從外部組件增強應用程式For more information, see 在 ASP.NET Core 中使用 IHostingStartup 從外部組件增強應用程式.

其他資源Additional resources