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

Rick AndersonKirk LarkinBy Rick Anderson and Kirk Larkin

ASP.NET Core 中的設定是使用一或多個設定 提供者來執行。Configuration in ASP.NET Core is performed using one or more configuration providers. 設定提供者會使用各種設定來源從機碼值組讀取設定資料:Configuration providers read configuration data from key-value pairs using a variety of configuration sources:

  • 設定檔案,例如 appsettings.jsonSettings files, such as appsettings.json
  • 環境變數Environment variables
  • Azure 金鑰保存庫Azure Key Vault
  • Azure 應用程式組態Azure App Configuration
  • 命令列引數Command-line arguments
  • 自訂提供者、已安裝或已建立Custom providers, installed or created
  • 目錄檔案Directory files
  • 記憶體內部 .NET 物件In-memory .NET objects

本主題提供 ASP.NET Core 中設定的相關資訊。This topic provides information on configuration in ASP.NET Core. 如需在主控台應用程式中使用設定的詳細資訊,請參閱 .net設定。For information on using configuration in console apps, see .NET Configuration.

查看或下載範例程式碼 (如何下載) View or download sample code (how to download)

預設組態Default configuration

ASP.NET Core 使用 dotnet new 或 Visual Studio 建立的 web 應用程式會產生下列程式碼:ASP.NET Core web apps created with dotnet new or Visual Studio generate the following code:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

CreateDefaultBuilder 會以下列順序提供應用程式的預設組態:CreateDefaultBuilder provides default configuration for the app in the following order:

  1. ChainedConfigurationProvider :加入現有的 IConfiguration 作為來源。ChainedConfigurationProvider : Adds an existing IConfiguration as a source. 在預設設定案例中,新增 主機 設定,並將其設定為 應用程式 設定的第一個來源。In the default configuration case, adds the host configuration and setting it as the first source for the app configuration.
  2. appsettings.json 使用 JSON 設定提供者appsettings.json using the JSON configuration provider.
  3. appsettings。 Environment使用 json 設定提供者json。appsettings.Environment.json using the JSON configuration provider. 例如, appsettings生產 * * _._jsonappsettings。 * * * 開發 _.json *。For example, appsettings.***Production**._json* and appsettings.***Development** _._json*.
  4. 應用程式在環境中執行時的應用程式秘密 DevelopmentApp secrets when the app runs in the Development environment.
  5. 使用 環境變數設定提供者的環境變數。Environment variables using the Environment Variables configuration provider.
  6. 使用 命令列設定提供者的命令列引數。Command-line arguments using the Command-line configuration provider.

稍後新增的設定提供者會覆寫先前的金鑰設定。Configuration providers that are added later override previous key settings. 例如,如果 MyKey 在和環境中設定 appsettings.json ,則會使用環境值。For example, if MyKey is set in both appsettings.json and the environment, the environment value is used. 使用預設的設定提供者, 命令列設定提供者 會覆寫所有其他提供者。Using the default configuration providers, the Command-line configuration provider overrides all other providers.

如需的詳細資訊 CreateDefaultBuilder ,請參閱 預設 builder 設定For more information on CreateDefaultBuilder, see Default builder settings.

下列程式碼會依新增的順序顯示已啟用的設定提供者:The following code displays the enabled configuration providers in the order they were added:

public class Index2Model : PageModel
{
    private IConfigurationRoot ConfigRoot;

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

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

        return Content(str);
    }
}

appsettings.json

請考慮下列檔案 appsettings.jsonConsider the following appsettings.json file:

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

範例下載中的下列程式碼會顯示上述幾個設定設定:The following code from the sample download displays several of the preceding configurations settings:

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

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

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


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

預設會 JsonConfigurationProvider 以下列順序載入設定:The default JsonConfigurationProvider loads configuration in the following order:

  1. appsettings.json
  2. appsettings。 Environment. json :例如 appsettings。**生產 * * _._json 和 *appsettings**** * * 開發 _.json * 檔案。appsettings.Environment.json : For example, the appsettings.***Production**._json* and appsettings.***Development** _._json* files. 檔案的環境版本是根據 IHostingEnvironment EnvironmentName載入。The environment version of the file is loaded based on the IHostingEnvironment.EnvironmentName. 如需詳細資訊,請參閱在 ASP.NET Core 中使用多個環境For more information, see 在 ASP.NET Core 中使用多個環境.

appsettings... Environmentjson 值會覆寫中的索引鍵 appsettings.jsonappsettings.Environment.json values override keys in appsettings.json. 例如,根據預設:For example, by default:

  • 在開發期間, appsettings. *開發 _._json * 設定會覆寫在中找到的值 appsettings.jsonIn development, appsettings.Development _._json configuration overwrites values found in appsettings.json.
  • 在生產環境中, appsettings. *生產 _._json * 設定會覆寫在中找到的值 appsettings.jsonIn production, appsettings.Production _._json configuration overwrites values found in appsettings.json. 例如,將應用程式部署至 Azure 時。For example, when deploying the app to Azure.

使用選項模式系結階層式設定資料Bind hierarchical configuration data using the options pattern

讀取相關設定值的慣用方法是使用選項模式The preferred way to read related configuration values is using the options pattern. 例如,若要讀取下列設定值:For example, to read the following configuration values:

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

建立下列 PositionOptions 類別:Create the following PositionOptions class:

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

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

選項類別:An options class:

  • 必須是非抽象,且具有公用無參數的函式。Must be non-abstract with a public parameterless constructor.
  • 類型的所有公用讀寫屬性都會系結。All public read-write properties of the type are bound.
  • 欄位系結。Fields are not bound. 在上述程式碼中, Position 不會系結。In the preceding code, Position is not bound. Position使用屬性,因此將類別系結 "Position" 至設定提供者時,不需要在應用程式中硬式編碼字串。The Position property is used so the string "Position" doesn't need to be hard coded in the app when binding the class to a configuration provider.

下列程式碼:The following code:

  • 呼叫ConfigurationBinder將類別系結 PositionOptionsPosition 區段。Calls ConfigurationBinder.Bind to bind the PositionOptions class to the Position section.
  • 顯示設定 Position 資料。Displays the Position configuration data.
public class Test22Model : PageModel
{
    private readonly IConfiguration Configuration;

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

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

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

在上述程式碼中,根據預設,會讀取應用程式啟動後對 JSON 設定檔進行的變更。In the preceding code, by default, changes to the JSON configuration file after the app has started are read.

ConfigurationBinder.Get<T>系結並傳回指定的型別。ConfigurationBinder.Get<T> binds and returns the specified type. ConfigurationBinder.Get<T>可能比使用更方便 ConfigurationBinder.BindConfigurationBinder.Get<T> may be more convenient than using ConfigurationBinder.Bind. 下列程式碼示範如何搭配使用 ConfigurationBinder.Get<T>PositionOptions 類別:The following code shows how to use ConfigurationBinder.Get<T> with the PositionOptions class:

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

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

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

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

在上述程式碼中,根據預設,會讀取應用程式啟動後對 JSON 設定檔進行的變更。In the preceding code, by default, changes to the JSON configuration file after the app has started are read.

使用 [選項] 模式時,另一種方法是系結 Position 區段,並將它加入至相依性插入服務容器An alternative approach when using the options pattern is to bind the Position section and add it to the dependency injection service container. 在下列程式碼中, PositionOptions 會新增至服務容器, Configure 並系結至設定:In the following code, PositionOptions is added to the service container with Configure and bound to configuration:

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

使用上述程式碼,下列程式碼會讀取位置選項:Using the preceding code, the following code reads the position options:

public class Test2Model : PageModel
{
    private readonly PositionOptions _options;

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

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

在上述程式碼中,會讀取在應用程式啟動後對 JSON 設定檔進行的變更。In the preceding code, changes to the JSON configuration file after the app has started are not read. 若要在應用程式啟動後讀取變更,請使用IOptionsSnapshotTo read changes after the app has started, use IOptionsSnapshot.

使用 預設設定, appsettings.json 以及 appsettings。 Environment已啟用 reloadOnChange: truejson 檔案。Using the default configuration, the appsettings.json and appsettings.Environment.json files are enabled with reloadOnChange: true. 對和 appsettings 進行的變更 appsettings.json Environmentjson 檔案 * 在 _ 之後json 設定提供者會讀取應用程式啟動。Changes made to the appsettings.json and appsettings.Environment.json file *after _ the app starts are read by the JSON configuration provider.

如需新增其他 JSON 設定檔的相關資訊,請參閱本檔中的 json 設定提供者See JSON configuration provider in this document for information on adding additional JSON configuration files.

合併服務集合Combining service collection

請考慮下列 ConfigureServices 方法,它會註冊服務並設定選項:Consider the following ConfigureServices method, which registers services and configures options:

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

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

    services.AddRazorPages();
}

您可以將相關的註冊群組移至擴充方法,以註冊服務。Related groups of registrations can be moved to an extension method to register services. 例如,設定服務會新增至下列類別:For example, the configuration services are added to the following class:

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

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

            return services;
        }
    }
}

其餘的服務會註冊在類似的類別中。The remaining services are registered in a similar class. 下列 ConfigureServices 方法會使用新的擴充方法來註冊服務:The following ConfigureServices method uses the new extension methods to register the services:

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

    services.AddRazorPages();
}

注意: 每個 services.Add{GROUP_NAME} 擴充方法會新增並可能設定服務。Note: Each services.Add{GROUP_NAME} extension method adds and potentially configures services. 例如, AddControllersWithViews 新增具有 views 所需的服務 MVC 控制器,並 AddRazorPages 新增 Razor Pages 所需的服務。For example, AddControllersWithViews adds the services MVC controllers with views require, and AddRazorPages adds the services Razor Pages requires. 建議應用程式遵循此命名慣例。We recommended that apps follow this naming convention. Microsoft.Extensions.DependencyInjection 命名空間中放置擴充方法,以封裝服務註冊群組。Place extension methods in the Microsoft.Extensions.DependencyInjection namespace to encapsulate groups of service registrations.

安全性與使用者秘密Security and user secrets

設定資料指導方針:Configuration data guidelines:

_ 絕對不要將密碼或其他敏感性資料儲存在設定提供者程式碼或純文字設定檔中。_ Never store passwords or other sensitive data in configuration provider code or in plain text configuration files. 秘密管理員工具可以用來在開發中儲存秘密。The Secret Manager tool can be used to store secrets in development.

  • 不要在開發或測試環境中使用生產環境祕密。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.

根據 預設,使用者秘密設定來源會在 JSON 設定來源之後註冊。By default, the user secrets configuration source is registered after the JSON configuration sources. 因此,使用者秘密金鑰優先于和 appsettings 中的金鑰 appsettings.json Environment. jsonTherefore, user secrets keys take precedence over keys in appsettings.json and appsettings.Environment.json.

如需有關儲存密碼或其他敏感性資料的詳細資訊:For more information on storing passwords or other sensitive data:

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

環境變數Environment variables

使用 預設設定時,會在 EnvironmentVariablesConfigurationProvider 讀取之後從環境變數機碼值組載入設定 appsettings.jsonappsettings)。 Environment. json使用者秘密Using the default configuration, the EnvironmentVariablesConfigurationProvider loads configuration from environment variable key-value pairs after reading appsettings.json, appsettings.Environment.json, and user secrets. 因此,從環境讀取的索引鍵值會覆寫 appsettings 中讀取的值 appsettings.json Environment. json 和使用者秘密。Therefore, key values read from the environment override values read from appsettings.json, appsettings.Environment.json, and user secrets.

:分隔符號不適用於所有平臺上的環境變數階層式索引鍵。The : separator doesn't work with environment variable hierarchical keys on all platforms. __(雙底線)為:__, the double underscore, is:

  • 所有平臺都支援。Supported by all platforms. 例如, : Bash不支援分隔符號,但 __ 為。For example, the : separator is not supported by Bash, but __ is.
  • 自動取代為 :Automatically replaced by a :

下列 set 命令:The following set commands:

  • 在 Windows 上設定 上述範例 的環境索引鍵和值。Set the environment keys and values of the preceding example on Windows.
  • 使用 範例下載時,測試設定。Test the settings when using the sample download. dotnet run命令必須在專案目錄中執行。The dotnet run command must be run in the project directory.
set MyKey="My key from Environment"
set Position__Title=Environment_Editor
set Position__Name=Environment_Rick
dotnet run

先前的環境設定:The preceding environment settings:

  • 只會在從其設定的命令視窗啟動的進程中設定。Are only set in processes launched from the command window they were set in.
  • 使用 Visual Studio 啟動的瀏覽器將無法讀取。Won't be read by browsers launched with Visual Studio.

您可以使用下列的 setx 命令,在 Windows 上設定環境機碼和值。The following setx commands can be used to set the environment keys and values on Windows. 與不同 setsetx 是,設定會持續保存。Unlike set, setx settings are persisted. /M 設定系統內容中的變數。/M sets the variable in the system environment. 如果 /M 未使用此參數,則會設定使用者環境變數。If the /M switch isn't used, a user environment variable is set.

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

若要測試上述命令是否覆寫 appsettings.jsonappsettings。 Environment. jsonTo test that the preceding commands override appsettings.json and appsettings.Environment.json:

  • 使用 Visual Studio: Exit 並重新啟動 Visual Studio。With Visual Studio: Exit and restart Visual Studio.
  • 使用 CLI:啟動新的命令視窗,然後輸入 dotnet runWith the CLI: Start a new command window and enter dotnet run.

AddEnvironmentVariables使用字串呼叫以指定環境變數的前置詞:Call AddEnvironmentVariables with a string to specify a prefix for environment variables:

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

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

在上述程式碼中:In the preceding code:

  • config.AddEnvironmentVariables(prefix: "MyCustomPrefix_") 會在預設設定 提供者之後加入。config.AddEnvironmentVariables(prefix: "MyCustomPrefix_") is added after the default configuration providers. 如需排序設定提供者的範例,請參閱 JSON 設定提供者For an example of ordering the configuration providers, see JSON configuration provider.
  • 具有前置詞的環境變數會覆 MyCustomPrefix_ 寫預設的設定 提供者Environment variables set with the MyCustomPrefix_ prefix override the default configuration providers. 這包括沒有前置詞的環境變數。This includes environment variables without the prefix.

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

下列命令會測試自訂前置詞:The following commands test the custom prefix:

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

預設設定會載入前面加上和的環境變數和命令列引數 DOTNET_ ASPNETCORE_The default configuration loads environment variables and command line arguments prefixed with DOTNET_ and ASPNETCORE_. 和前置詞 DOTNET_ ASPNETCORE_ 是由 ASP.NET Core 用於 主機和應用程式設定,但不適用於使用者設定。The DOTNET_ and ASPNETCORE_ prefixes are used by ASP.NET Core for host and app configuration, but not for user configuration. 如需有關主機和應用程式設定的詳細資訊,請參閱 .Net 泛型主機For more information on host and app configuration, see .NET Generic Host.

Azure App Service上,選取 [設定 > 設定] 頁面上的 [新增應用程式設定]。On Azure App Service, select New application setting on the Settings > Configuration page. Azure App Service 的應用程式設定如下:Azure App Service application settings are:

  • 靜態加密,並透過加密通道傳輸。Encrypted at rest and transmitted over an encrypted channel.
  • 公開為環境變數。Exposed as environment variables.

如需詳細資訊,請參閱 Azure App:使用 Azure 入口網站覆寫應用程式設定For more information, see Azure Apps: Override app configuration using the Azure Portal.

如需 Azure 資料庫連接字串的相關資訊,請參閱 連接字串 前置詞。See Connection string prefixes for information on Azure database connection strings.

環境變數的命名Naming of environment variables

環境變數名稱會反映檔案的結構 appsettings.jsonEnvironment variable names reflect the structure of an appsettings.json file. 階層中的每個元素會以雙底線分隔 (偏好) 或冒號。Each element in the hierarchy is separated by a double underscore (preferable) or a colon. 當元素結構包含陣列時,應該將陣列索引視為這個路徑中的其他元素名稱。When the element structure includes an array, the array index should be treated as an additional element name in this path. 請考慮下列檔案 appsettings.json 及其對等的值(以環境變數表示)。Consider the following appsettings.json file and its equivalent values represented as environment variables.

appsettings.json

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

環境變數environment variables

setx SmtpServer=smtp.example.com
setx Logging__0__Name=ToEmail
setx Logging__0__Level=Critical
setx Logging__0__Args__FromAddress=MySystem@example.com
setx Logging__0__Args__ToAddress=SRE@example.com
setx Logging__1__Name=ToConsole
setx Logging__1__Level=Information

在 launchSettings.js中設定的環境變數Environment variables set in launchSettings.json

launchSettings.js 中設定的環境變數會覆寫系統內容中所設定的環境變數。Environment variables set in launchSettings.json override those set in the system environment.

命令列Command-line

使用 預設 設定時,會 CommandLineConfigurationProvider 從命令列引數索引鍵/值組在下列設定來源之後載入設定:Using the default configuration, the CommandLineConfigurationProvider loads configuration from command-line argument key-value pairs after the following configuration sources:

  • appsettings.jsonappsettingsEnvironmentjson 檔案。appsettings.json and appsettings.Environment.json files.
  • 開發環境中的應用程式秘密App secrets in the Development environment.
  • 環境變數。Environment variables.

根據 預設,在命令列覆寫設定值設定的設定值會與所有其他設定提供者一起設定。By default, configuration values set on the command-line override configuration values set with all the other configuration providers.

命令列引數Command-line arguments

下列命令會使用下列命令來設定索引鍵和值 =The following command sets keys and values using =:

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

下列命令會使用下列命令來設定索引鍵和值 /The following command sets keys and values using /:

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

下列命令會使用下列命令來設定索引鍵和值 --The following command sets keys and values using --:

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

索引鍵值:The key value:

  • 必須遵循 = ,或者 -- / 當值在空格後面時,索引鍵必須有或的前置詞。Must follow =, or the key must have a prefix of -- or / when the value follows a space.
  • 如果 = 使用,則不需要。Isn't required if = is used. 例如 MySetting=For example, MySetting=.

在相同的命令中,不要混用 = 與使用空格的索引鍵/值組搭配使用的命令列引數索引鍵/值配對。Within the same command, don't mix command-line argument key-value pairs that use = with key-value pairs that use a space.

切換對應Switch mappings

交換器對應允許索引 名稱取代邏輯。Switch mappings allow key name replacement logic. 為方法提供切換取代的字典 AddCommandLineProvide 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 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 - or --.
  • 切換對應字典不能包含重複索引鍵。The switch mappings dictionary must not contain duplicate keys.

若要使用切換對應字典,請將它傳遞到的呼叫中 AddCommandLineTo use a switch mappings dictionary, pass it into the call to AddCommandLine:

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

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

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

下列程式碼顯示已取代金鑰的索引鍵值:The following code shows the key values for the replaced keys:

public class Test3Model : PageModel
{
    private readonly IConfiguration Config;

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

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

下列命令適用于測試金鑰取代:The following command works to test key replacement:

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

針對使用切換對應的應用程式,呼叫 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.

階層式設定資料Hierarchical configuration data

設定 API 會透過使用設定金鑰中的分隔符號來簡維階層式資料,以讀取階層式設定資料。The Configuration API reads hierarchical configuration data by flattening the hierarchical data with the use of a delimiter in the configuration keys.

範例下載包含下列檔案 appsettings.jsonThe sample download contains the following appsettings.json file:

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

範例下載中的下列程式碼會顯示數個設定設定:The following code from the sample download displays several of the configurations settings:

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

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

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


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

讀取階層式設定資料的慣用方式是使用選項模式。The preferred way to read hierarchical configuration data is using the options pattern. 如需詳細資訊,請參閱本檔中的系結階層式設定 資料For more information, see Bind hierarchical configuration data in this document.

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.

設定機碼和值Configuration keys and values

設定金鑰:Configuration keys:

  • 不區分大小寫。Are case-insensitive. 例如,ConnectionStringconnectionstring 會被視為相等的機碼。For example, ConnectionString and connectionstring are treated as equivalent keys.
  • 如果在多個設定提供者中設定索引鍵和值,則會使用最後新增的提供者所提供的值。If a key and value is set in more than one configuration providers, the value from the last provider added is used. 如需詳細資訊,請參閱 預設設定。For more information, see Default configuration.
  • 階層式機碼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 -- as a separator. Azure Key Vault configuration provider -- : 當秘密載入至應用程式的設定時,Azure Key Vault 設定提供者會自動取代為。The Azure Key Vault configuration provider automatically replaces -- with a : 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:

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

設定提供者Configuration 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 Azure 金鑰保存庫Azure Key Vault
Azure App 設定提供者Azure App configuration provider 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 檔案INI, JSON, and XML files
每個檔案的金鑰配置提供者Key-per-file configuration provider 目錄檔案Directory files
記憶體設定提供者Memory configuration provider 記憶體內集合In-memory collections
使用者秘密User secrets 使用者設定檔目錄中的檔案File in the user profile directory

設定來源會依照其設定提供者的指定順序讀取。Configuration sources are read in the order that their configuration providers are specified. 在程式碼中訂購設定提供者,以符合應用程式所需之基礎設定來源的優先順序。Order configuration providers in code to suit the priorities for the underlying configuration sources that the app requires.

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

  1. appsettings.json
  2. appsettings... Environmentjsonappsettings.Environment.json
  3. 使用者秘密User secrets
  4. 使用 環境變數設定提供者的環境變數。Environment variables using the Environment Variables configuration provider.
  5. 使用 命令列設定提供者的命令列引數。Command-line arguments using the Command-line configuration provider.

常見的作法是將命令列設定提供者新增至一系列的提供者,以允許命令列引數覆寫其他提供者所設定的設定。A common practice is to add the Command-line configuration provider last in a series of providers to allow command-line arguments to override configuration set by the other providers.

先前的提供者序列會用於 預設設定中。The preceding sequence of providers is used in the default configuration.

連接字串前置詞Connection string prefixes

設定 API 有四個連接字串環境變數的特殊處理規則。The Configuration API has special processing rules for four connection string environment variables. 這些連接字串涉及設定應用程式環境的 Azure 連接字串。These connection strings are involved in configuring Azure connection strings for the app environment. 具有資料表中所顯示前置詞的環境變數會以 預設 設定載入至應用程式,或不提供任何前置詞 AddEnvironmentVariablesEnvironment variables with the prefixes shown in the table are loaded into the app with the default configuration or when 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. 以下是衍生自的設定提供者 FileConfigurationProviderThe following configuration providers derive from FileConfigurationProvider:

INI 設定提供者INI configuration provider

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

下列程式碼會清除所有設定提供者,並新增數個設定提供者:The following code clears all the configuration providers and adds several configuration providers:

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

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

                var env = hostingContext.HostingEnvironment;

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

                config.AddEnvironmentVariables();

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

在上述程式碼中, MyIniConfig.iniMyIniConfig 中的設定 Environment 。中的設定會覆寫 ini 檔案:In the preceding code, settings in the MyIniConfig.ini and MyIniConfig.Environment.ini files are overridden by settings in the:

範例下載包含下列 MyIniConfig.ini 檔案:The sample download contains the following MyIniConfig.ini file:

MyKey="MyIniConfig.ini Value"

[Position]
Title="My INI Config title"
Name="My INI Config name"

[Logging:LogLevel]
Default=Information
Microsoft=Warning

範例下載中的下列程式碼會顯示上述幾個設定設定:The following code from the sample download displays several of the preceding configurations settings:

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

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

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


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

JSON 設定提供者JSON configuration provider

JsonConfigurationProvider 從 JSON 檔案機碼值組載入設定。The JsonConfigurationProvider loads configuration from JSON file key-value pairs.

多載可以指定:Overloads can specify:

  • 檔案是否為選擇性。Whether the file is optional.
  • 檔案變更時是否要重新載入設定。Whether the configuration is reloaded if the file changes.

請考慮下列程式碼:Consider the following code:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("MyConfig.json", 
                    optional: true, 
                    reloadOnChange: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

上述程式碼:The preceding code:

您通常 需要使用自訂 JSON 檔案來覆寫 環境變數設定提供者命令列設定提供者中所設定的值。You typically *don't _ want a custom JSON file overriding values set in the Environment variables configuration provider and the Command-line configuration provider.

下列程式碼會清除所有設定提供者,並新增數個設定提供者:The following code clears all the configuration providers and adds several configuration providers:

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

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

                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
                                     optional: true, reloadOnChange: true);

                config.AddJsonFile("MyConfig.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"MyConfig.{env.EnvironmentName}.json",
                                     optional: true, reloadOnChange: true);

                config.AddEnvironmentVariables();

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

在上述程式碼中,_MyConfig.js中的設定為 * ** and myconfig.xml Environmentjson 檔案:In the preceding code, settings in the _MyConfig.json* and MyConfig.Environment.json files:

範例下載包含檔案上的下列 MyConfig.jsThe sample download contains the following MyConfig.json file:

{
    "Position": {
        "Title": "我的設定標題",
        "Name": "My Config Smith"
    },
    "MyKey": "MyConfig.json Value",
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*"
}

範例下載中的下列程式碼會顯示上述幾個設定設定:The following code from the sample download displays several of the preceding configurations settings:

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

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

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


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

XML 設定提供者XML configuration provider

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

下列程式碼會清除所有設定提供者,並新增數個設定提供者:The following code clears all the configuration providers and adds several configuration providers:

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

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

                var env = hostingContext.HostingEnvironment;

                config.AddXmlFile("MyXMLFile.xml", optional: true, reloadOnChange: true)
                      .AddXmlFile($"MyXMLFile.{env.EnvironmentName}.xml",
                                     optional: true, reloadOnChange: true);

                config.AddEnvironmentVariables();

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

在上述程式碼中, MyXMLFile.xmlMyXMLFile 中的設定 Environment 。中的設定會覆寫 xml 檔案:In the preceding code, settings in the MyXMLFile.xml and MyXMLFile.Environment.xml files are overridden by settings in the:

範例下載包含下列 MyXMLFile.xml 檔案:The sample download contains the following MyXMLFile.xml file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <MyKey>MyXMLFile Value</MyKey>
  <Position>
    <Title>Title from  MyXMLFile</Title>
    <Name>Name from MyXMLFile</Name>
  </Position>
  <Logging>
    <LogLevel>
      <Default>Information</Default>
      <Microsoft>Warning</Microsoft>
    </LogLevel>
  </Logging>
</configuration>

範例下載中的下列程式碼會顯示上述幾個設定設定:The following code from the sample download displays several of the preceding configurations settings:

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

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

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


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

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 00</key>
    <key name="key1">value 01</key>
  </section>
  <section name="section1">
    <key name="key0">value 10</key>
    <key name="key1">value 11</key>
  </section>
</configuration>

下列程式碼會讀取先前的設定檔,並顯示金鑰和值:The following code reads the previous configuration file and displays the keys and values:

public class IndexModel : PageModel
{
    private readonly IConfiguration Configuration;

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

    public ContentResult OnGet()
    {
        var key00 = "section:section0:key:key0";
        var key01 = "section:section0:key:key1";
        var key10 = "section:section1:key:key0";
        var key11 = "section:section1:key:key1";

        var val00 = Configuration[key00];
        var val01 = Configuration[key01];
        var val10 = Configuration[key10];
        var val11 = Configuration[key11];

        return Content($"{key00} value: {val00} \n" +
                       $"{key01} value: {val01} \n" +
                       $"{key10} value: {val10} \n" +
                       $"{key10} value: {val11} \n"
                       );
    }
}

屬性可用來提供值: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) =>
{
    var path = Path.Combine(
        Directory.GetCurrentDirectory(), "path/to/files");
    config.AddKeyPerFile(directoryPath: path, optional: true);
})

記憶體設定提供者Memory configuration provider

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

下列程式碼會將記憶體集合新增至設定系統:The following code adds a memory collection to the configuration system:

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

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        var Dict = new Dictionary<string, string>
        {
           {"MyKey", "Dictionary MyKey Value"},
           {"Position:Title", "Dictionary_Title"},
           {"Position:Name", "Dictionary_Name" },
           {"Logging:LogLevel:Default", "Warning"}
        };

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

範例下載中的下列程式碼會顯示上述設定設定:The following code from the sample download displays the preceding configurations settings:

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

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

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


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

在上述程式碼中, config.AddInMemoryCollection(Dict) 是在 預設設定提供者之後加入。In the preceding code, config.AddInMemoryCollection(Dict) is added after the default configuration providers. 如需排序設定提供者的範例,請參閱 JSON 設定提供者For an example of ordering the configuration providers, see JSON configuration provider.

請參閱使用 將陣列 系結到另一個範例 MemoryConfigurationProviderSee Bind an array for another example using MemoryConfigurationProvider.

GetValueGetValue

ConfigurationBinder.GetValue<T> 從具有指定索引鍵的設定中解壓縮單一值,並將其轉換為指定的類型:ConfigurationBinder.GetValue<T> extracts a single value from configuration with a specified key and converts it to the specified type:

public class TestNumModel : PageModel
{
    private readonly IConfiguration Configuration;

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

    public ContentResult OnGet()
    {
        var number = Configuration.GetValue<int>("NumberKey", 99);
        return Content($"{number}");
    }
}

在上述程式碼中,如果在設定 NumberKey 中找不到, 99 就會使用的預設值。In the preceding code, if NumberKey isn't found in the configuration, the default value of 99 is used.

GetSection、GetChildren 與 ExistsGetSection, GetChildren, and Exists

針對接下來的範例,請考慮下列 MySubsection.json file:For the examples that follow, consider the following MySubsection.json file:

{
  "section0": {
    "key0": "value00",
    "key1": "value01"
  },
  "section1": {
    "key0": "value10",
    "key1": "value11"
  },
  "section2": {
    "subsection0": {
      "key0": "value200",
      "key1": "value201"
    },
    "subsection1": {
      "key0": "value210",
      "key1": "value211"
    }
  }
}

下列程式碼會將 MySubsection.js 新增至設定提供者:The following code adds MySubsection.json to the configuration providers:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("MySubsection.json", 
                    optional: true, 
                    reloadOnChange: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

GetSectionGetSection

IConfiguration 會傳回具有指定之子區段索引鍵的設定子區段。IConfiguration.GetSection returns a configuration subsection with the specified subsection key.

下列程式碼會傳回的值 section1The following code returns values for section1:

public class TestSectionModel : PageModel
{
    private readonly IConfiguration Config;

    public TestSectionModel(IConfiguration configuration)
    {
        Config = configuration.GetSection("section1");
    }

    public ContentResult OnGet()
    {
        return Content(
                $"section1:key0: '{Config["key0"]}'\n" +
                $"section1:key1: '{Config["key1"]}'");
    }
}

下列程式碼會傳回的值 section2:subsection0The following code returns values for section2:subsection0:

public class TestSection2Model : PageModel
{
    private readonly IConfiguration Config;

    public TestSection2Model(IConfiguration configuration)
    {
        Config = configuration.GetSection("section2:subsection0");
    }

    public ContentResult OnGet()
    {
        return Content(
                $"section2:subsection0:key0 '{Config["key0"]}'\n" +
                $"section2:subsection0:key1:'{Config["key1"]}'");
    }
}

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.

GetChildren 和 ExistsGetChildren and Exists

下列程式碼會呼叫 IConfiguration GetChildren ,並傳回 section2:subsection0 下列值:The following code calls IConfiguration.GetChildren and returns values for section2:subsection0:

public class TestSection4Model : PageModel
{
    private readonly IConfiguration Config;

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

    public ContentResult OnGet()
    {
        string s = null;
        var selection = Config.GetSection("section2");
        if (!selection.Exists())
        {
            throw new System.Exception("section2 does not exist.");
        }
        var children = selection.GetChildren();

        foreach (var subSection in children)
        {
            int i = 0;
            var key1 = subSection.Key + ":key" + i++.ToString();
            var key2 = subSection.Key + ":key" + i.ToString();
            s += key1 + " value: " + selection[key1] + "\n";
            s += key2 + " value: " + selection[key2] + "\n";
        }
        return Content(s);
    }
}

上述程式碼會呼叫 >microsoft.extensions.options.configurationextensions ,以確認區段存在:The preceding code calls ConfigurationExtensions.Exists to verify the section exists:

系結陣列Bind an array

ConfigurationBinder支援使用設定索引鍵中的陣列索引,將陣列系結至物件。The ConfigurationBinder.Bind supports binding arrays to objects using array indices in configuration keys. 任何公開數位索引鍵區段的陣列格式都能夠將陣列系結至 POCO 類別陣列。Any array format that exposes a numeric key segment is capable of array binding to a POCO class array.

請考慮從 範例下載MyArray.jsConsider MyArray.json from the sample download:

{
  "array": {
    "entries": {
      "0": "value00",
      "1": "value10",
      "2": "value20",
      "4": "value40",
      "5": "value50"
    }
  }
}

下列程式碼會將 MyArray.js 新增至設定提供者:The following code adds MyArray.json to the configuration providers:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("MyArray.json", 
                    optional: true, 
                    reloadOnChange: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

下列程式碼會讀取設定,並顯示這些值:The following code reads the configuration and displays the values:

public class ArrayModel : PageModel
{
    private readonly IConfiguration Config;
    public ArrayExample _array { get; private set; }

    public ArrayModel(IConfiguration config)
    {
        Config = config;
    }

    public ContentResult OnGet()
    {
        _array = Config.GetSection("array").Get<ArrayExample>();
        string s = null;

        for (int j = 0; j < _array.Entries.Length; j++)
        {
            s += $"Index: {j}  Value:  {_array.Entries[j]} \n";
        }

        return Content(s);
    }
}

上述程式碼會傳回下列輸出:The preceding code returns the following output:

Index: 0  Value: value00
Index: 1  Value: value10
Index: 2  Value: value20
Index: 3  Value: value40
Index: 4  Value: value50

在上述輸出中,索引3具有值 value40 ,對應于 "4": "value40", MyArray.js 中的。In the preceding output, Index 3 has value value40, corresponding to "4": "value40", in MyArray.json. 系結陣列索引是連續的,不會系結至設定索引鍵索引。The bound array indices are continuous and not bound to the configuration key index. 設定系結器無法系結 null 值,或在系結物件中建立 null 專案The configuration binder isn't capable of binding null values or creating null entries in bound objects

下列程式碼會 array:entries 使用 AddInMemoryCollection 擴充方法載入設定:The following code loads the array:entries configuration with the AddInMemoryCollection extension method:

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

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        var arrayDict = new Dictionary<string, string>
        {
            {"array:entries:0", "value0"},
            {"array:entries:1", "value1"},
            {"array:entries:2", "value2"},
            //              3   Skipped
            {"array:entries:4", "value4"},
            {"array:entries:5", "value5"}
        };

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

下列程式碼會讀取中的設定 arrayDict Dictionary ,並顯示這些值:The following code reads the configuration in the arrayDict Dictionary and displays the values:

public class ArrayModel : PageModel
{
    private readonly IConfiguration Config;
    public ArrayExample _array { get; private set; }

    public ArrayModel(IConfiguration config)
    {
        Config = config;
    }

    public ContentResult OnGet()
    {
        _array = Config.GetSection("array").Get<ArrayExample>();
        string s = null;

        for (int j = 0; j < _array.Entries.Length; j++)
        {
            s += $"Index: {j}  Value:  {_array.Entries[j]} \n";
        }

        return Content(s);
    }
}

上述程式碼會傳回下列輸出:The preceding code returns the following output:

Index: 0  Value: value0
Index: 1  Value: value1
Index: 2  Value: value2
Index: 3  Value: value4
Index: 4  Value: value5

繫結物件中的索引 #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 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 索引鍵/值組的任何設定提供者,在系結至實例之前,提供索引3的遺漏設定專案。The missing configuration item for index #3 can be supplied before binding to the ArrayExample instance by any configuration provider that reads the index #3 key/value pair. 請考慮下列來自範例下載的檔案 Value3.jsConsider the following Value3.json file from the sample download:

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

下列程式碼包含與的 Value3.js 設定 arrayDict DictionaryThe following code includes configuration for Value3.json and the arrayDict Dictionary:

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

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        var arrayDict = new Dictionary<string, string>
        {
            {"array:entries:0", "value0"},
            {"array:entries:1", "value1"},
            {"array:entries:2", "value2"},
            //              3   Skipped
            {"array:entries:4", "value4"},
            {"array:entries:5", "value5"}
        };

        return Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddInMemoryCollection(arrayDict);
                config.AddJsonFile("Value3.json",
                                    optional: false, reloadOnChange: false);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    }
}

下列程式碼會讀取先前的設定,並顯示這些值:The following code reads the preceding configuration and displays the values:

public class ArrayModel : PageModel
{
    private readonly IConfiguration Config;
    public ArrayExample _array { get; private set; }

    public ArrayModel(IConfiguration config)
    {
        Config = config;
    }

    public ContentResult OnGet()
    {
        _array = Config.GetSection("array").Get<ArrayExample>();
        string s = null;

        for (int j = 0; j < _array.Entries.Length; j++)
        {
            s += $"Index: {j}  Value:  {_array.Entries[j]} \n";
        }

        return Content(s);
    }
}

上述程式碼會傳回下列輸出:The preceding code returns the following output:

Index: 0  Value: value0
Index: 1  Value: value1
Index: 2  Value: value2
Index: 3  Value: value3
Index: 4  Value: value4
Index: 5  Value: value5

自訂設定提供者不需要實作陣列繫結。Custom configuration providers aren't required to implement array binding.

自訂設定提供者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:

// using Microsoft.EntityFrameworkCore;

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:

// using Microsoft.EntityFrameworkCore;
// using Microsoft.Extensions.Configuration;

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. 由於設定索引 鍵不區分大小寫,因此用來初始化資料庫的字典會以不區分大小寫的比較子來建立 (stringcomparison. OrdinalIgnoreCase) 。Since configuration keys are case-insensitive, the dictionary used to initialize the database is created with the case-insensitive comparer (StringComparer.OrdinalIgnoreCase).

EFConfigurationProvider/EFConfigurationProvider.csEFConfigurationProvider/EFConfigurationProvider.cs:

// using Microsoft.EntityFrameworkCore;
// using Microsoft.Extensions.Configuration;

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

    Action<DbContextOptionsBuilder> OptionsAction { get; }

    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>(StringComparer.OrdinalIgnoreCase)
            {
                { "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:

// using Microsoft.EntityFrameworkCore;
// using Microsoft.Extensions.Configuration;

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:

// using Microsoft.EntityFrameworkCore;

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddEFConfiguration(
                options => options.UseInMemoryDatabase("InMemoryDb"));
        })

在啟動時存取設定Access configuration in Startup

下列程式碼會在方法中顯示設定資料 StartupThe following code displays configuration data in Startup methods:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        Console.WriteLine($"MyKey : {Configuration["MyKey"]}");
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        Console.WriteLine($"Position:Title : {Configuration["Position:Title"]}");

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

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

存取頁面中的設定 RazorAccess configuration in Razor Pages

下列程式碼會在頁面中顯示設定資料 Razor :The following code displays configuration data in a Razor Page:

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

Configuration value for 'MyKey': @Configuration["MyKey"]

在下列程式碼中, MyOptions 會新增至服務容器, Configure 並系結至設定:In the following code, MyOptions is added to the service container with Configure and bound to configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));

    services.AddRazorPages();
}

下列標記會使用指示詞 @inject Razor 來解析和顯示選項值:The following markup uses the @inject Razor directive to resolve and display the options values:

@page
@model SampleApp.Pages.Test3Model
@using Microsoft.Extensions.Options
@inject IOptions<MyOptions> optionsAccessor


<p><b>Option1:</b> @optionsAccessor.Value.Option1</p>
<p><b>Option2:</b> @optionsAccessor.Value.Option2</p>

MVC view 檔案中的存取設定Access configuration in a MVC view file

下列程式碼會顯示 MVC 視圖中的設定資料:The following code displays configuration data in a MVC view:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

Configuration value for 'MyKey': @Configuration["MyKey"]

使用委派設定選項Configure options with a delegate

在委派中設定的選項會覆寫設定提供者中所設定的值。Options configured in a delegate override values set in the configuration providers.

使用委派來設定選項,會示範為範例應用程式中的範例2。Configuring options with a delegate is demonstrated as Example 2 in the sample app.

在下列程式碼中, IConfigureOptions<TOptions> 服務會新增至服務容器。In the following code, an IConfigureOptions<TOptions> service is added to the service container. 它會使用委派來設定下列值 MyOptionsIt uses a delegate to configure values for MyOptions:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MyOptions>(myOptions =>
    {
        myOptions.Option1 = "Value configured in delegate";
        myOptions.Option2 = 500;
    });

    services.AddRazorPages();
}

下列程式碼會顯示選項值:The following code displays the options values:

public class Test2Model : PageModel
{
    private readonly IOptions<MyOptions> _optionsDelegate;

    public Test2Model(IOptions<MyOptions> optionsDelegate )
    {
        _optionsDelegate = optionsDelegate;
    }

    public ContentResult OnGet()
    {
        return Content($"Option1: {_optionsDelegate.Value.Option1} \n" +
                       $"Option2: {_optionsDelegate.Value.Option2}");
    }
}

在上述範例中,和的值 Option1 Option2 是在中指定, appsettings.json 然後由設定的委派覆寫。In the preceding example, the values of Option1 and Option2 are specified in appsettings.json and then overridden by the configured delegate.

主機與應用程式組態的比較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 host configuration

如需使用 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.

其他設定Other configuration

本主題僅適用于 應用程式 設定。This topic only pertains to app configuration. 執行和主控 ASP.NET Core 應用程式的其他層面,是使用本主題未涵蓋的設定檔來設定:Other aspects of running and hosting ASP.NET Core apps are configured using configuration files not covered in this topic:

launchSettings.js 中設定的環境變數會覆寫系統內容中所設定的環境變數。Environment variables set in launchSettings.json override those set in the system environment.

如需從舊版 ASP.NET 遷移應用程式設定的詳細資訊,請參閱 從 ASP.NET 移轉至 ASP.NET CoreFor more information on migrating app configuration from earlier versions of ASP.NET, see 從 ASP.NET 移轉至 ASP.NET Core.

從外部組件新增設定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

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 金鑰保存庫Azure 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) 的組態套件包含在 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 基本概念.

其他設定Other configuration

本主題僅適用于 應用程式 設定。This topic only pertains to app configuration. 執行和主控 ASP.NET Core 應用程式的其他層面,是使用本主題未涵蓋的設定檔來設定:Other aspects of running and hosting ASP.NET Core apps are configured using configuration files not covered in this topic:

如需從舊版 ASP.NET 遷移應用程式設定的詳細資訊,請參閱 從 ASP.NET 移轉至 ASP.NET CoreFor more information on migrating app configuration from earlier versions of ASP.NET, see 從 ASP.NET 移轉至 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:

下列項目適用於使用 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 頁面 PageModel 或 MVC Controller ,以取得類別的設定。IConfiguration can be injected into a Razor Pages PageModel or MVC Controller to obtain configuration for the class.

在下列範例中, _config 會使用欄位來存取設定值:In the following examples, the _config field is used to access configuration values:

public class IndexModel : PageModel
{
    private readonly IConfiguration _config;

    public IndexModel(IConfiguration config)
    {
        _config = config;
    }
}
public class HomeController : Controller
{
    private readonly IConfiguration _config;

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

設定提供者無法使用 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. 如需重複的 JSON 金鑰的詳細資訊,請參閱 此 GitHub 問題For more information on duplicate JSON keys, see this GitHub issue.
  • 階層式機碼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. 撰寫程式碼,以在將秘密載入至應用程式的設定時,以冒號取代虛線。Write 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 金鑰保存庫Azure 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 (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 the code arranges them. 在程式碼中訂購設定提供者,以符合應用程式所需之基礎設定來源的優先順序。Order configuration providers in code to suit the priorities for the underlying configuration sources that the app requires.

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

  1. 檔案 (appsettings.jsonappsettings. {環境} json,其中 {Environment} 是應用程式目前的裝載環境) Files (appsettings.json, appsettings.{Environment}.json, where {Environment} is the app's current hosting environment)
  2. Azure 金鑰保存庫Azure Key Vault
  3. 僅) (開發環境的使用者秘密User secrets (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.

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

使用 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)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                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);
})

移除 >createdefaultbuilder 新增的提供者Remove providers added by CreateDefaultBuilder

若要移除新增的提供者 CreateDefaultBuilder ,請在IConfigurationBuilder上呼叫Clear first:To remove the providers added by CreateDefaultBuilder, call Clear on the IConfigurationBuilder.Sources first:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.Sources.Clear();
    // Add providers here
})

在應用程式啟動期間使用組態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 的選擇性設定 appsettings.json 。環境}. json 檔案。Optional configuration from appsettings.json and appsettings.{Environment}.json files.
  • 開發環境中的使用者秘密User secrets 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 ,請提供方法的切換替代字典 AddCommandLineWhen manually building configuration with a ConfigurationBuilder, 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.

機碼Key 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.

機碼Key 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.

:分隔符號不適用於所有平臺上的環境變數階層式索引鍵。The : separator doesn't work with environment variable hierarchical keys on all platforms. __(雙底線)為:__, the double underscore, is:

  • 所有平臺都支援。Supported by all platforms. 例如, : Bash不支援分隔符號,但 __ 為。For example, the : separator is not supported by Bash, but __ is.
  • 自動取代為 :Automatically replaced by a :

Azure App Service 允許在 Azure 入口網站中設定可使用環境變數設定提供者覆寫應用程式設定的環境變數。Azure App Service permits setting 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.

使用 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 的選擇性設定 appsettings.json 。環境}. json 檔案。Optional configuration from appsettings.json and appsettings.{Environment}.json files.
  • 開發環境中的使用者秘密User secrets 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 並使用前置詞來呼叫 AddEnvironmentVariablesTo provide app configuration from additional environment variables, call the app's additional providers in ConfigureAppConfiguration and call AddEnvironmentVariables with the prefix:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddEnvironmentVariables(prefix: "PREFIX_");
})

呼叫 AddEnvironmentVariables last 以允許具有指定前置詞的環境變數覆寫其他提供者的值。Call AddEnvironmentVariables last to allow environment variables with the given prefix to override values from other providers.

範例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.

若要將所有可用的環境變數公開給應用程式,請 FilteredConfigurationPages/Index. .cs 變更為下列內容: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

在提供方法的前置詞時,會篩選載入至應用程式設定的環境變數 AddEnvironmentVariablesEnvironment variables loaded into the app's configuration are filtered when supplying 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

範例Example

在伺服器上建立自訂連接字串環境變數:A custom connection string environment variable is created on the server:

  • 名稱:CUSTOMCONNSTR_ReleaseDBName: CUSTOMCONNSTR_ReleaseDB
  • 值:Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=TrueValue: Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True

如果 IConfiguration 插入並指派給名為的欄位 _config ,請閱讀下列值:If IConfiguration is injected and assigned to a field named _config, read the value:

_config["ConnectionStrings:ReleaseDB"]

檔案設定提供者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.AddIniFile(
        "config.ini", optional: true, reloadOnChange: true);
})

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.

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

  • appsettings.json:先讀取此檔案。appsettings.json: This file is read first. 檔案的環境版本可以覆寫檔案所提供的值 appsettings.jsonThe environment version of the file can override the values provided by the appsettings.json file.
  • appsettings。{環境}. 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:

  • 環境變數。Environment variables.
  • 開發環境中的使用者秘密User secrets in the Development environment.
  • 命令列引數。Command-line arguments.

會先建立 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 以外的檔案指定應用程式的設定時,請呼叫 appsettings.json 。 {環境}. jsonCall 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.AddJsonFile(
        "config.json", optional: true, reloadOnChange: true);
})

範例Example

範例應用程式會利用靜態的便利性方法 CreateDefaultBuilder 來建立主機,其中包含兩個對的呼叫 AddJsonFileThe sample app takes advantage of the static convenience method CreateDefaultBuilder to build the host, which includes two calls to AddJsonFile:

  • 從下列載入設定的第一個呼叫 AddJsonFile appsettings.jsonThe first call to AddJsonFile loads configuration from appsettings.json:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    
  • 從 appsettings 載入設定的第二個呼叫 AddJsonFile 。 {環境}. jsonThe second call to AddJsonFile loads configuration from appsettings.{Environment}.json. 針對範例應用程式中的 appsettings.Development.js ,會載入下列檔案:For appsettings.Development.json in the sample app, the following file is loaded:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Debug",
          "System": "Information",
          "Microsoft": "Information"
        }
      }
    }
    
  1. 執行範例應用程式。Run the sample app. 開啟瀏覽器以瀏覽位於 http://localhost:5000 的應用程式。Open a browser to the app at http://localhost:5000.
  2. 輸出會根據應用程式的環境,包含設定的機碼值組。The output contains key-value pairs for the configuration based on the app's environment. 金鑰的記錄層級 Logging:LogLevel:Default 是在 Debug 開發環境中執行應用程式時。The log level for the key Logging:LogLevel:Default is Debug when running the app in the Development environment.
  3. 在生產環境中再次執行範例應用程式:Run the sample app again in the Production environment:
    1. 開啟檔案的 屬性/launchSettings.jsOpen the Properties/launchSettings.json file.
    2. ConfigurationSample 設定檔中,將環境變數的值變更 ASPNETCORE_ENVIRONMENTProductionIn the ConfigurationSample profile, change the value of the ASPNETCORE_ENVIRONMENT environment variable to Production.
    3. 使用命令介面儲存檔案,並 dotnet run 在中執行應用程式。Save the file and run the app with dotnet run in a command shell.
  4. appsettings.Development.js 中的設定不會再覆寫中的設定 appsettings.jsonThe settings in the appsettings.Development.json no longer override the settings in appsettings.json. 索引鍵的記錄層級 Logging:LogLevel:DefaultWarningThe log level for the key Logging:LogLevel:Default is Warning.

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.AddXmlFile(
        "config.xml", optional: true, reloadOnChange: true);
})

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) =>
{
    var path = Path.Combine(
        Directory.GetCurrentDirectory(), "path/to/files");
    config.AddKeyPerFile(directoryPath: path, optional: true);
})

記憶體設定提供者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> 從具有指定索引鍵的設定中解壓縮單一值,並將其轉換為指定的 noncollection 類型。ConfigurationBinder.GetValue<T> extracts a single value from configuration with a specified key and converts it to the specified noncollection type. 多載接受預設值。An overload accepts a default value.

下列範例將: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();

ExistsExists

使用 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 an object graph

Bind 可以繫結整個 POCO 物件圖形。Bind is capable of binding an entire POCO object graph. 如同系結簡單的物件,只會系結公用讀取/寫入屬性。As with binding a simple object, only public read/write properties are bound.

範例包含 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; }
}

範例應用程式有 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>

設定會被繫結到整個 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:

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.

機碼Key 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)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                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; }
}

設定資料已繫結到物件: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的執行個體) 會從設定接收陣列資料。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.

機碼Key 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 設定提供者」會將設定資料讀入到下列機碼值組:The JSON Configuration Provider reads the configuration data into the following key-value pairs:

機碼Key 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; }
}

在繫結之後,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>(StringComparer.OrdinalIgnoreCase)
            {
                { "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.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 頁面頁面或 MVC 視圖中的設定Access configuration in a Razor Pages page or MVC view

若要存取 Razor 頁面頁面或 MVC 視圖中的設定設定,請新增 using 指示詞 (c # 參考:使用 Microsoft.Extensions.Configuration 命名空間 的指示詞) ,然後插入 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