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

查看或下載範例程式碼如何下載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. 使用json 設定提供者appsettings。appsettings.json using the JSON configuration provider.
  3. appsettings。 Environment使用json 設定提供者jsonappsettings.Environment.json using the JSON configuration provider. 例如, appsettings生產jsonappsettings開發jsonFor 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和環境中設定,則會使用環境值。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 ,請參閱預設產生器設定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.jsonappsettings.json

請考慮下列appsettings json檔案:Consider 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.jsonappsettings.json
  2. appsettings。 Environment. json :例如, appsettings生產jsonappsettings開發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 中使用多個環境.

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

  • 在開發中, appsettings開發json設定會覆寫在appsettings中找到的值。In development, appsettings.Development.json configuration overwrites values found in appsettings.json.
  • 在生產環境中, appsettings生產json設定會覆寫在appsettings中找到的值。In 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.

使用預設設定,即appsettingsappsettings。 Environment已啟用reloadOnChange: truejson檔案。Using the default configuration, the appsettings.json and appsettings.Environment.json files are enabled with reloadOnChange: true. appsettings和 appsettings 所做的變更 Environment應用程式啟動json檔案會由 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.

安全性和秘密管理員Security and secret manager

設定資料方針:Configuration data guidelines:

  • 永遠不要將密碼或其他敏感性資料儲存在設定提供者程式碼或純文字設定檔中。Never store passwords or other sensitive data in configuration provider code or in plain text configuration files. 秘密管理員可以用來將秘密儲存在開發中。The Secret manager 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.

根據預設秘密管理員會在appsettings之後讀取設定和appsettings。 Environment. jsonBy default, Secret manager reads configuration settings after 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. 如需詳細資訊,請參閱<xref:security/key-vault-configuration>。For more information, see <xref:security/key-vault-configuration>.

環境變數Environment variables

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

:分隔符不適用於所有平臺上的環境變數分層鍵。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

若要測試前面的命令會覆寫appsettingsappsettings。 Environment. jsonTo test that the preceding commands override appsettings.json and appsettings.Environment.json:

  • 使用 Visual Studio: [結束] 和 [重新開機] 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.

命令列Command-line

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

根據預設,在命令列上設定的設定值會覆寫所有其他設定提供者所設定的設定值。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. 將參數取代的字典提供給 AddCommandLine 方法。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 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"]}'");
    }
}

執行下列命令來測試金鑰取代:Run the following command to test the key replacement:

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

注意:目前 = 無法使用單一破折號來設定索引鍵取代值 -Note: Currently, = cannot be used to set key-replacement values with a single dash -. 請參閱這個 GitHub 問題See this GitHub issue.

下列命令適用于測試金鑰取代: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檔案:The 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 | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

---- |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:---- | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

------------------ || Azure Key Vault 設定提供者|Azure Key Vault || Azure App 設定提供者|Azure 應用程式組態 ||命令列設定提供者|命令列參數 ||自訂設定提供者|自訂來源 ||環境變數設定提供者|環境變數 |檔案設定 | 提供者|INI、JSON 和 XML 檔案 ||每個檔案的索引鍵設定提供者 |目錄檔案 ||記憶體設定提供者|記憶體內部集合 ||秘密管理員|使用者設定檔目錄中的檔案 |------------------ | | Azure Key Vault configuration provider | Azure Key Vault | | Azure App configuration provider | Azure App Configuration | | Command-line configuration provider | Command-line parameters | | Custom configuration provider | Custom source | | Environment Variables configuration provider | Environment variables | | File configuration provider | INI, JSON, and XML files | | Key-per-file configuration provider | Directory files | | Memory configuration provider | In-memory collections | | Secret Manager | 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.jsonappsettings.json
  2. appsettingsEnvironmentjsonappsettings.Environment.json
  3. 秘密管理員Secret Manager
  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 | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

------------ |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:------------ | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

---- || CUSTOMCONNSTR_ |自訂提供者 || MYSQLCONNSTR_ |MySQL | MySQL |SQLAZURECONNSTR_ | Azure SQL Database | | SQLCONNSTR_ | SQL Server|---- | | CUSTOMCONNSTR_ | Custom provider | | MYSQLCONNSTR_ | MySQL | | SQLAZURECONNSTR_ | Azure SQL Database | | SQLCONNSTR_ | SQL 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 | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

------------ |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:------------ | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-------------- |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:-------------- | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

---------------------------------------- | |CUSTOMCONNSTR_{KEY} | ConnectionStrings:{KEY} |未建立設定專案。---------------------------------------- | | CUSTOMCONNSTR_{KEY} | ConnectionStrings:{KEY} | Configuration entry not created. | |MYSQLCONNSTR_{KEY} | ConnectionStrings:{KEY} |機碼 ConnectionStrings:{KEY}_ProviderName| | MYSQLCONNSTR_{KEY} | ConnectionStrings:{KEY} | Key: ConnectionStrings:{KEY}_ProviderName:
值: MySql.Data.MySqlClient | | SQLAZURECONNSTR_{KEY} | ConnectionStrings:{KEY} |機碼 ConnectionStrings:{KEY}_ProviderNameValue: MySql.Data.MySqlClient | | SQLAZURECONNSTR_{KEY} | ConnectionStrings:{KEY} | Key: ConnectionStrings:{KEY}_ProviderName:
值: System.Data.SqlClient | | SQLCONNSTR_{KEY} | ConnectionStrings:{KEY} |機碼 ConnectionStrings:{KEY}_ProviderNameValue: System.Data.SqlClient | | SQLCONNSTR_{KEY} | ConnectionStrings:{KEY} | Key: ConnectionStrings:{KEY}_ProviderName:
ValueSystem.Data.SqlClient |Value: System.Data.SqlClient |

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.xml中的設定和myconfig.xml Environmentjson檔案:In the preceding code, settings in the MyConfig.json and MyConfig.Environment.json files:

範例下載包含下列myconfig.xml檔案:The 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}");
    }
}

檔案設定提供者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>();
            });
}

在上述程式碼中, MyIniConfigMyIniConfig中的 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}");
    }
}

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

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

範例下載包含下列MyXMLFile檔案: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 中找不到,則會使用的預設值 99In 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檔: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新增至設定提供者: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。 GetSection會傳回具有指定子區段索引鍵的設定子區段。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:subsection0The 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.

請考慮範例下載中的MyArrayConsider MyArray.json from the sample download:

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

下列程式碼會將MyArray新增至設定提供者: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中的。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 使用擴充方法來載入設定 AddInMemoryCollectionThe 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.

在系 # 結至實例之前,您可以先提供索引3的遺漏設定專案 ArrayExample ,以讀取索引 # 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 json檔案:Consider the following Value3.json file from the sample download:

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

下列程式碼包含Value3的設定和 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:

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. 由於設定索引鍵不區分大小寫,用來初始化資料庫的字典會以不區分大小寫的比較子(StringComparer. 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:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.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);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

啟動時的存取設定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 視圖檔案中的存取設定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中指定,然後由設定的委派覆寫。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:

  • 啟動 json /launchsettings.json是開發環境的工具設定檔,如下所述:launch.json/launchSettings.json are tooling configuration files for the Development environment, described:
  • web.config是伺服器設定檔,如下列主題所述:web.config is a server configuration file, described in the following topics:
    • <xref:host-and-deploy/iis/index>
    • <xref:host-and-deploy/aspnet-core-module>

如需從舊版 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. 如需詳細資訊,請參閱<xref:fundamentals/configuration/platform-specific-configuration>。For more information, see <xref:fundamentals/configuration/platform-specific-configuration>.

其他資源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. 如需詳細資訊,請參閱<xref:fundamentals/configuration/options>。For more information, see <xref:fundamentals/configuration/options>.

查看或下載範例程式碼如何下載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:

  • 啟動 json /launchsettings.json是開發環境的工具設定檔,如下所述:launch.json/launchSettings.json are tooling configuration files for the Development environment, described:
  • web.config是伺服器設定檔,如下列主題所述:web.config is a server configuration file, described in the following topics:
    • <xref:host-and-deploy/iis/index>
    • <xref:host-and-deploy/aspnet-core-module>

如需從舊版 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. 如需詳細資訊,請參閱<xref:security/key-vault-configuration>。For more information, see <xref:security/key-vault-configuration>.

階層式設定資料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.
  • 階層式機碼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… | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

---- |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:---- | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

------------------ || Azure Key Vault 設定提供者安全性主題) |Azure Key Vault || Azure 應用程式組態提供者(Azure 檔) |Azure 應用程式組態 ||命令列設定提供者|命令列參數 ||自訂設定提供者|自訂來源 ||環境變數設定提供者|環境變數 |檔案設定 | 提供者|檔案(INI、JSON、XML) ||每個檔案的索引鍵設定提供者 |目錄檔案 ||記憶體設定提供者|記憶體內部集合 ||使用者秘密(秘密管理員)安全性主題) |使用者設定檔目錄中的檔案 |------------------ | | Azure Key Vault Configuration Provider (Security topics) | Azure Key Vault | | Azure App Configuration Provider (Azure documentation) | Azure App Configuration | | Command-line Configuration Provider | Command-line parameters | | Custom configuration provider | Custom source | | Environment Variables Configuration Provider | Environment variables | | File Configuration Provider | Files (INI, JSON, XML) | | Key-per-file Configuration Provider | Directory files | | Memory Configuration Provider | In-memory collections | | User secrets (Secret Manager) (Security topics) | File in the user profile directory |

在啟動時,會依照設定來源的設定提供者的指定順序讀入設定來源。Configuration sources are read in the order that their configuration providers are specified at startup. 本主題所描述的設定提供者會依字母順序描述,而不是程式碼排列它們的順序。The configuration providers described in this topic are described in alphabetical order, not in the order that 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. Files (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 (Secret Manager) (Development environment only)
  4. 環境變數Environment variables
  5. 命令列引數Command-line arguments

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

當使用初始化新的主機產生器時,會使用上述的提供者序列 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上呼叫ClearTo 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.jsonappsettings.{Environment}.json 檔案載入其他選擇性組態。Optional configuration from appsettings.json and appsettings.{Environment}.json files.
  • 開發環境中的使用者祕密 (祕密管理員)User secrets (Secret Manager) in the Development environment.
  • 環境變數。Environment variables.

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

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

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

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

範例Example

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

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

引數Arguments

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

| 索引鍵前置字元Key prefix | 範例Example | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

------------ |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:------------ | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

--------------------------- | |沒有前置詞 |CommandLineKey1=value1 | |雙虛線( -- ) | --CommandLineKey2=value2--CommandLineKey2 value2 | |正斜線( / ) | /CommandLineKey3=value3/CommandLineKey3 value3 |--------------------------- | | No prefix | CommandLineKey1=value1 | | Two dashes (--) | --CommandLineKey2=value2, --CommandLineKey2 value2 | | Forward slash (/) | /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.

| KeyKey | Value | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

----- |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:----- | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

--------- | | -CLKey1 | CommandLineKey1 | | -CLKey2 | CommandLineKey2 |--------- | | -CLKey1 | CommandLineKey1 | | -CLKey2 | CommandLineKey2 |

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

dotnet run -CLKey1=value1 -CLKey2=value2

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

| KeyKey | Value | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

--------- |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:--------- | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

---- | | CommandLineKey1 | value1 | | CommandLineKey2 | value2 |---- | | 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.jsonappsettings.{Environment}.json 檔案載入其他選擇性組態。Optional configuration from appsettings.json and appsettings.{Environment}.json files.
  • 開發環境中的使用者祕密 (祕密管理員)User secrets (Secret Manager) in the Development environment.
  • 命令列引數。Command-line arguments.

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

若要從其他環境變數提供應用程式設定,請在中呼叫應用程式的其他提供者, ConfigureAppConfigurationAddEnvironmentVariables 使用前置詞呼叫:To provide app configuration from additional environment variables, call the app's additional providers in ConfigureAppConfiguration and call AddEnvironmentVariables with the prefix:

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

AddEnvironmentVariables最後呼叫以允許具有指定前置詞的環境變數,覆寫其他提供者的值。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.

若要公開應用程式可用的所有環境變數,請將 FilteredConfiguration Pages/Index. cshtml中的變更為下列內容: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 | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

------------ |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:------------ | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

---- || CUSTOMCONNSTR_ |自訂提供者 || MYSQLCONNSTR_ |MySQL | MySQL |SQLAZURECONNSTR_ | Azure SQL Database | | SQLCONNSTR_ | SQL Server|---- | | CUSTOMCONNSTR_ | Custom provider | | MYSQLCONNSTR_ | MySQL | | SQLAZURECONNSTR_ | Azure SQL Database | | SQLCONNSTR_ | SQL 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 | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

------------ |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:------------ | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-------------- |---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:-------------- | --- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

---------------------------------------- | |CUSTOMCONNSTR_{KEY} | ConnectionStrings:{KEY} |未建立設定專案。---------------------------------------- | | CUSTOMCONNSTR_{KEY} | ConnectionStrings:{KEY} | Configuration entry not created. | |MYSQLCONNSTR_{KEY} | ConnectionStrings:{KEY} |機碼 ConnectionStrings:{KEY}_ProviderName| | MYSQLCONNSTR_{KEY} | ConnectionStrings:{KEY} | Key: ConnectionStrings:{KEY}_ProviderName:
值: MySql.Data.MySqlClient | | SQLAZURECONNSTR_{KEY} | ConnectionStrings:{KEY} |機碼 ConnectionStrings:{KEY}_ProviderNameValue: MySql.Data.MySqlClient | | SQLAZURECONNSTR_{KEY} | ConnectionStrings:{KEY} | Key: ConnectionStrings:{KEY}_ProviderName:
值: System.Data.SqlClient | | SQLCONNSTR_{KEY} | ConnectionStrings:{KEY} |機碼 ConnectionStrings:{KEY}_ProviderNameValue: System.Data.SqlClient | | SQLCONNSTR_{KEY} | ConnectionStrings:{KEY} | Key: ConnectionStrings:{KEY}_ProviderName:
ValueSystem.Data.SqlClient |Value: 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:先讀取此檔案。appsettings.json: This file is read first. 檔案的環境版本可以覆寫由 appsettings.json 檔案提供的值。The environment version of the file can override the values provided by the appsettings.json file.
  • appsettings。{環境}. json:檔案的環境版本是根據IHostingEnvironment. EnvironmentName載入。appsettings.{Environment}.json: The environment version of the file is loaded based on the IHostingEnvironment.EnvironmentName.

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

CreateDefaultBuilder 也會載入:CreateDefaultBuilder also loads:

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

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

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.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:

  • 第一次呼叫時,會 AddJsonFileappsettings載入設定:The first call to AddJsonFile loads configuration from appsettings.json:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    
  • 第二個呼叫會 AddJsonFile 從 appsettings 載入設定 。 {環境}. jsonThe second call to AddJsonFile loads configuration from appsettings.{Environment}.json. 適用于appsettings。 範例應用程式中的開發 json 會載入下列檔案: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. 開啟Properties/launchsettings.json檔案。Open 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 在命令 shell 中使用來執行應用程式。Save the file and run the app with dotnet run in a command shell.
  4. Appsettings 中的設定 appsettings中,不會再覆寫 json 中的設定。The 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.

| KeyKey | Value | | :--- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-------: |:----: | |陣列:專案: 0 |value0 | |陣列:專案: 1 |value1 | |陣列:專案: 2 |value2 | |陣列:專案: 4 |value4 | |陣列:專案: 5 |value5 |-------: | :----: | | array:entries:0 | value0 | | array:entries:1 | value1 | | array:entries:2 | value2 | | array:entries:4 | value4 | | array:entries:5 | value5 |

這些機碼與值是使用「記憶體設定提供者」在範例應用程式中載入: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 | | :--- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-------------: |:---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:-------------: | :--- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-------------: | |0 |value0 | |1 |value1 | |2 |value2 | |3 |value4 | |4 |value5 |-------------: | | 0 | value0 | | 1 | value1 | | 2 | value2 | | 3 | value4 | | 4 | 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 merely used to iterate the configuration data when creating the object. 設定資料中不能保留 Null 值,當設定機碼中的陣列略過一或多個索引時,不會在繫結物件中建立 Null 值項目。A null value can't be retained in configuration data, and a null-valued entry isn't created in a bound object when an array in configuration keys skip one or more indices.

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

missing_value.jsonmissing_value.json:

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

ConfigureAppConfiguration 中:In ConfigureAppConfiguration:

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

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

| KeyKey | Value | | :--- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-------: |:----: | |陣列:專案: 3 |value3 |-------: | :----: | | array:entries:3 | value3 |

在「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 | | :--- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-------------: |:---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:-------------: | :--- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-------------: | |0 |value0 | |1 |value1 | |2 |value2 | |3 |value3 | |4 |value4 | |5 |value5 |-------------: | | 0 | value0 | | 1 | value1 | | 2 | value2 | | 3 | value3 | | 4 | value4 | | 5 | value5 |

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:

| KeyKey | Value | | --- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

------------ |:----: | |json_array:索引鍵 |valueA | |json_array:小節: 0 |valueB | |json_array:小節: 1 |Valuec&parameter2 | |json_array:小節: 2 |值 |------------ | :----: | | json_array:key | valueA | | json_array:subsection:0 | valueB | | json_array:subsection:1 | valueC | | json_array:subsection:2 | valueD |

在範例應用程式中,下列 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 | | :--- 標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-----------------: |:---標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:-----------------: | :--- title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'

  • 'Identity''Identity'

  • 'Let's Encrypt''Let's Encrypt'

  • 'Razor''Razor'

  • ' SignalR ' uid:'SignalR' uid:

標題: author: description: monikerRange: ms-chap: ms. custom: ms. date: no-loc:title: author: description: monikerRange: ms.author: ms.custom: ms.date: no-loc:

  • 'Blazor''Blazor'
  • 'Identity''Identity'
  • 'Let's Encrypt''Let's Encrypt'
  • 'Razor''Razor'
  • ' SignalR ' uid:'SignalR' uid:

-----------------: | |0 |valueB | |1 |Valuec&parameter2 | |2 |值 |-----------------: | | 0 | valueB | | 1 | valueC | | 2 | valueD |

自訂設定提供者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 # 參考: using指示詞),並將其插入 IConfiguration 頁面或視圖中。To access configuration settings in a Razor Pages page or an MVC view, add a using directive (C# reference: using directive) for the Microsoft.Extensions.Configuration namespace and inject IConfiguration into the page or view.

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

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

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

在 MVC 檢視中:In an MVC view:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

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

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

IHostingStartup 實作允許在啟動時從應用程式 Startup 類別外部的外部組件,針對應用程式新增增強功能。An IHostingStartup implementation allows adding enhancements to an app at startup from an external assembly outside of the app's Startup class. 如需詳細資訊,請參閱<xref:fundamentals/configuration/platform-specific-configuration>。For more information, see <xref:fundamentals/configuration/platform-specific-configuration>.

其他資源Additional resources

  • <xref:fundamentals/configuration/options>