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

作者:Rick AndersonMark MichaelisSteve SmithDaniel RothLuke LathamBy Rick Anderson, Mark Michaelis, Steve Smith, Daniel Roth, and Luke Latham

組態 API 可讓您根據成對的名稱和數值清單來設定 ASP.NET Core Web 應用程式。The Configuration API provides a way to configure an ASP.NET Core web app based on a list of name-value pairs. 組態是在執行階段讀取自多個來源。Configuration is read at runtime from multiple sources. 成對的名稱和數值可以分組成多重層級階層。Name-value pairs can be grouped into a multi-level hierarchy.

下列項目有組態提供者:There are configuration providers for:

  • 檔案格式 (INI、JSON 及 XML)。File formats (INI, JSON, and XML).
  • 命令列引數。Command-line arguments.
  • 環境變數。Environment variables.
  • 記憶體內部 .NET 物件。In-memory .NET objects.
  • 未加密的祕密管理員儲存體。The unencrypted Secret Manager storage.
  • 類似 Azure Key Vault的加密使用者存放區。An encrypted user store, such as Azure Key Vault.
  • 自訂提供者 (已安裝或已建立)。Custom providers (installed or created).

每個組態值會對應至一個字串索引鍵。Each configuration value maps to a string key. 還有內建繫結支援可將設定還原序列化為自訂 POCO 物件 (具有屬性的簡單 .NET 類別)。There's built-in binding support to deserialize settings into a custom POCO object (a simple .NET class with properties).

選項模式使用選項類別來代表一組相關的設定。The options pattern uses options classes to represent groups of related settings. 如需使用選項模式的詳細資訊,請參閱選項主題。For more information on using the options pattern, see the Options topic.

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

本主題提供的範例需要:Examples provided in this topic rely upon:

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

本主題提供的範例需要:Examples provided in this topic rely upon:

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

本主題提供的範例需要:Examples provided in this topic rely upon:

JSON 組態JSON configuration

下列主控台應用程式使用 JSON 組態提供者:The following console app uses the JSON configuration provider:

using System;
using System.IO;
// Requires NuGet package
// Microsoft.Extensions.Configuration.Json
using Microsoft.Extensions.Configuration;

public class Program
{
    public static IConfiguration Configuration { get; set; }

    public static void Main(string[] args = null)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();

        Console.WriteLine($"option1 = {Configuration["Option1"]}");
        Console.WriteLine($"option2 = {Configuration["option2"]}");
        Console.WriteLine(
            $"suboption1 = {Configuration["subsection:suboption1"]}");
        Console.WriteLine();

        Console.WriteLine("Wizards:");
        Console.Write($"{Configuration["wizards:0:Name"]}, ");
        Console.WriteLine($"age {Configuration["wizards:0:Age"]}");
        Console.Write($"{Configuration["wizards:1:Name"]}, ");
        Console.WriteLine($"age {Configuration["wizards:1:Age"]}");
        Console.WriteLine();

        Console.WriteLine("Press a key...");
        Console.ReadKey();
    }
}

此應用程式會讀取並顯示下列組態設定:The app reads and displays the following configuration settings:

{
  "option1": "value1_from_json",
  "option2": 2,

  "subsection": {
    "suboption1": "subvalue1_from_json"
  },
  "wizards": [
    {
      "Name": "Gandalf",
      "Age": "1000"
    },
    {
      "Name": "Harry",
      "Age": "17"
    }
  ]
}

組態是由成對的名稱和數值階層式清單所組成,其中節點是以冒號分隔 (:)。Configuration consists of a hierarchical list of name-value pairs in which the nodes are separated by a colon (:). 若要擷取值,請使用對應項目的索引鍵來存取 Configuration 索引子:To retrieve a value, access the Configuration indexer with the corresponding item's key:

Console.WriteLine(
    $"suboption1 = {Configuration["subsection:suboption1"]}");

若要使用 JSON 格式組態來源中的陣列,請使用陣列索引作為冒號分隔字串的一部分。To work with arrays in JSON-formatted configuration sources, use an array index as part of the colon-separated string. 下列範例會取得上述 wizards 陣列中第一個項目的名稱:The following example gets the name of the first item in the preceding wizards array:

Console.Write($"{Configuration["wizards:0:Name"]}");
// Output: Gandalf

寫入內建組態提供者的成對名稱和數值不會保存。Name-value pairs written to the built-in Configuration providers are not persisted. 不過,可以建立自訂提供者來儲存值。However, a custom provider that saves values can be created. 請參閱自訂組態提供者See custom configuration provider.

上述範例使用 Configuration 索引子來讀取值。The preceding sample uses the configuration indexer to read values. 若要存取 Startup 外部組態,請使用「選項模式」。To access configuration outside of Startup, use the options pattern. 如需詳細資訊,請參閱選項主題。For more information, see the Options topic.

XML 組態XML configuration

若要在 XML 格式的組態來源中使用陣列,請為各元素提供 name 索引。To work with arrays in XML-formatted configuration sources, provide a name index to each element. 使用索引存取值:Use the index to access the values:

<wizards>
  <wizard name="Gandalf">
    <age>1000</age>
  </wizard>
  <wizard name="Harry">
    <age>17</age>
  </wizard>
</wizards>
Console.Write($"{Configuration["wizard:Harry:age"]}");
// Output: 17

取決於環境的組態Configuration by environment

不同的環境 (例如開發、測試和生產) 通常會有不同的組態設定。It's typical to have different configuration settings for different environments, for example, development, testing, and production. ASP.NET Core 2.x 應用程式中的 CreateDefaultBuilder 擴充方法 (或在 ASP.NET Core 1.x 應用程式中直接使用 AddJsonFileAddEnvironmentVariables) 會新增組態提供者以讀取 JSON 檔案和系統組態來源:The CreateDefaultBuilder extension method in an ASP.NET Core 2.x app (or using AddJsonFile and AddEnvironmentVariables directly in an ASP.NET Core 1.x app) adds configuration providers for reading JSON files and system configuration sources:

  • appsettings.jsonappsettings.json
  • appsettings.<環境名稱>.jsonappsettings.<EnvironmentName>.json
  • 環境變數Environment variables

ASP.NET Core 1.x 應用程式需要呼叫 AddJsonFileAddEnvironmentVariablesASP.NET Core 1.x apps need to call AddJsonFile and AddEnvironmentVariables.

如需參數的說明,請參閱 AddJsonFileSee AddJsonFile for an explanation of the parameters. reloadOnChange 只有在 ASP.NET Core 1.1 和更新版本中才支援。reloadOnChange is only supported in ASP.NET Core 1.1 and later.

組態來源是依其指定順序讀取。Configuration sources are read in the order that they're specified. 在上述程式碼中,環境變數最後才會讀取。In the preceding code, the environment variables are read last. 在環境中設定的任何組態值會取代在上述兩個提供者中設定的值。Any configuration values set through the environment replace those set in the two previous providers.

請考慮使用下列 appsettings.Staging.json 檔案:Consider the following appsettings.Staging.json file:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "MyConfig": "My Config Value for staging."
}

在下列程式碼中,Configure 會讀取 MyConfig 的值:In the following code, Configure reads the value of MyConfig:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var myConfig = Configuration["MyConfig"];
    // use myConfig
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }

    if (env.IsProduction() || env.IsStaging())
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();
}

環境通常會設定為 DevelopmentStagingProductionThe environment is typically set to Development, Staging, or Production. 如需詳細資訊,請參閱使用多重環境For more information, see Use multiple environments.

組態考量:Configuration considerations:

  • IOptionsSnapshot 可在組態資料變更時重新載入資料。IOptionsSnapshot can reload configuration data when it changes.
  • 組態金鑰區分大小寫。Configuration keys are not case-sensitive.
  • 永遠不要將密碼或其他敏感性資料儲存在組態提供者程式碼或純文字組態檔中。Never store passwords or other sensitive data in configuration provider code or in plain text configuration files. 不要在開發或測試環境中使用生產環境祕密。Don't use production secrets in development or test environments. 請在專案外部指定祕密,以防止其意外認可至開放原始碼存放庫。Specify secrets outside of the project so that they can't be accidentally committed to a source code repository. 深入了解如何使用多重環境以及管理開發期間安全儲存應用程式祕密Learn more about how to use multiple environments and managing safe storage of app secrets in development.
  • 若為環境變數中指定的階層式組態值,冒號 (:) 可能無法在所有平台上運作。For hierarchical config values specified in environment variables, a colon (:) may not work on all platforms. 所有平台皆支援雙底線 (__)。Double underscore (__) is supported by all platforms.
  • 與組態 API 互動時,冒號 (:) 可在所有平台上運作。When interacting with the configuration API, a colon (:) works on all platforms.

記憶體內部提供者和 POCO 類別的繫結In-memory provider and binding to a POCO class

下列範例示範如何使用記憶體內部提供者,並繫結至一個類別:The following sample shows how to use the in-memory provider and bind to a class:

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;

public class Program
{   
    public static IConfiguration Configuration { get; set; }

    public static void Main(string[] args = null)
    {
        var dict = new Dictionary<string, string>
            {
                {"Profile:MachineName", "Rick"},
                {"App:MainWindow:Height", "11"},
                {"App:MainWindow:Width", "11"},
                {"App:MainWindow:Top", "11"},
                {"App:MainWindow:Left", "11"}
            };

        var builder = new ConfigurationBuilder();
        builder.AddInMemoryCollection(dict);

        Configuration = builder.Build();

        Console.WriteLine($"Hello {Configuration["Profile:MachineName"]}");

        var window = new MyWindow();
        // Bind requrires NuGet package
        // Microsoft.Extensions.Configuration.Binder
        Configuration.GetSection("App:MainWindow").Bind(window);
        Console.WriteLine($"Left {window.Left}");
        Console.WriteLine();

        Console.WriteLine("Press any key...");
        Console.ReadKey();
    }
}

public class MyWindow
{
    public int Height { get; set; }
    public int Width { get; set; }
    public int Top { get; set; }
    public int Left { get; set; }
}

組態值是以字串傳回,但繫結會啟用物件的建構。Configuration values are returned as strings, but binding enables the construction of objects. 使用繫結即可擷取 POCO 物件,甚至是整個物件圖形。Binding allows the retrieval of POCO objects or even entire object graphs.

GetValueGetValue

下列範例示範 GetValue<T> 擴充方法:The following sample demonstrates the GetValue<T> extension method:

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;

public class Program
{   
    public static IConfiguration Configuration { get; set; }

    public static void Main(string[] args = null)
    {
        var dict = new Dictionary<string, string>
            {
                {"Profile:MachineName", "Rick"},
                {"App:MainWindow:Height", "11"},
                {"App:MainWindow:Width", "11"},
                {"App:MainWindow:Top", "11"},
                {"App:MainWindow:Left", "11"}
            };

        var builder = new ConfigurationBuilder();
        builder.AddInMemoryCollection(dict);

        Configuration = builder.Build();

        Console.WriteLine($"Hello {Configuration["Profile:MachineName"]}");

        // Show GetValue overload and set the default value to 80
        // Requires NuGet package "Microsoft.Extensions.Configuration.Binder"
        var left = Configuration.GetValue<int>("App:MainWindow:Left", 80);
        Console.WriteLine($"Left {left}");

        var window = new MyWindow();
        Configuration.GetSection("App:MainWindow").Bind(window);
        Console.WriteLine($"Left {window.Left}");
        Console.WriteLine();

        Console.WriteLine("Press a key...");
        Console.ReadKey();
    }
}

public class MyWindow
{
    public int Height { get; set; }
    public int Width { get; set; }
    public int Top { get; set; }
    public int Left { get; set; }
}

使用 ConfigurationBinder 的 GetValue<T> 方法可指定預設值 (在範例中為 80)。The ConfigurationBinder's GetValue<T> method allows the specification of a default value (80 in the sample). GetValue<T> 適用於簡單的案例,並不會繫結至整個區段。GetValue<T> is for simple scenarios and doesn't bind to entire sections. GetValue<T> 會從轉換成特定類型的 GetSection(key).Value 取得純量值。GetValue<T> obtains scalar values from GetSection(key).Value converted to a specific type.

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

類別中的每個物件都可以遞迴繫結。Each object in a class can be recursively bound. 請考慮下列 AppSettings 類別:Consider the following AppSettings class:

public class AppSettings
{
    public Window Window { get; set; }
    public Connection Connection { get; set; }
    public Profile Profile { get; set; }
}

public class Window
{
    public int Height { get; set; }
    public int Width { get; set; }
}

public class Connection
{
    public string Value { get; set; }
}

public class Profile
{
    public string Machine { get; set; }
}

下列範例會繫結至 AppSettings 類別:The following sample binds to the AppSettings class:

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

public class Program
{
    public static void Main(string[] args = null)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        var config = builder.Build();

        var appConfig = new AppSettings();
        config.GetSection("App").Bind(appConfig);

        Console.WriteLine($"Height {appConfig.Window.Height}");
        Console.WriteLine();

        Console.WriteLine("Press a key...");
        Console.ReadKey();
    }
}

ASP.NET Core 1.1 和更新版本可以使用 Get<T>,這適用於整個區段。ASP.NET Core 1.1 and higher can use Get<T>, which works with entire sections. Get<T> 可能比使用 Bind 更方便。Get<T> can be more convenient than using Bind. 下列程式碼示範如何在上述範例中使用 Get<T>The following code shows how to use Get<T> with the preceding sample:

var appConfig = config.GetSection("App").Get<AppSettings>();

使用下列 appsettings.json 檔案:Using the following appsettings.json file:

{
  "App": {
    "Profile": {
      "Machine": "Rick"
    },
    "Connection": {
      "Value": "connectionstring"
    },
    "Window": {
      "Height": "11",
      "Width": "11"
    }
  }
}

此程式會顯示 Height 11The program displays Height 11.

下列程式碼可用於組態的單元測試:The following code can be used to unit test the configuration:

[Fact]
public void CanBindObjectTree()
{
    var dict = new Dictionary<string, string>
        {
            {"App:Profile:Machine", "Rick"},
            {"App:Connection:Value", "connectionstring"},
            {"App:Window:Height", "11"},
            {"App:Window:Width", "11"}
        };
    var builder = new ConfigurationBuilder();
    builder.AddInMemoryCollection(dict);
    var config = builder.Build();

    var settings = new AppSettings();
    config.GetSection("App").Bind(settings);

    Assert.Equal("Rick", settings.Profile.Machine);
    Assert.Equal(11, settings.Window.Height);
    Assert.Equal(11, settings.Window.Width);
    Assert.Equal("connectionstring", settings.Connection.Value);
}

建立 Entity Framework 自訂提供者Create an Entity Framework custom provider

在本節中,會建立從使用 EF 的資料庫讀取成對的名稱和數值的基本組態提供者。In this section, a basic configuration provider that reads name-value pairs from a database using EF is created.

定義 ConfigurationValue 實體來將組態值儲存在資料庫中:Define a ConfigurationValue entity for storing configuration values in the database:

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

新增 ConfigurationContext 來儲存及存取所設定的值:Add a ConfigurationContext to store and access the configured values:

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

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

建立實作 IConfigurationSource 的類別:Create a class that implements IConfigurationSource:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace CustomConfigurationProvider
{
    public class EFConfigSource : IConfigurationSource
    {
        private readonly Action<DbContextOptionsBuilder> _optionsAction;

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

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

透過繼承自 ConfigurationProvider 來建立自訂組態提供者。Create the custom configuration provider by inheriting from ConfigurationProvider. 組態提供者會將空白資料庫初始化:The configuration provider initializes the database when it's empty:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

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

        Action<DbContextOptionsBuilder> OptionsAction { get; }

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

            using (var dbContext = new ConfigurationContext(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(
            ConfigurationContext dbContext)
        {
            var configValues = new Dictionary<string, string>
                {
                    { "key1", "value_from_ef_1" },
                    { "key2", "value_from_ef_2" }
                };
            dbContext.Values.AddRange(configValues
                .Select(kvp => new ConfigurationValue { Id = kvp.Key, Value = kvp.Value })
                .ToArray());
            dbContext.SaveChanges();
            return configValues;
        }
    }
}

執行範例時,會顯示資料庫中醒目提示的值 ("value_from_ef_1" 和 "value_from_ef_2") 。The highlighted values from the database ("value_from_ef_1" and "value_from_ef_2") are displayed when the sample is run.

EFConfigSource 擴充方法可以用來新增組態來源:An EFConfigSource extension method for adding the configuration source can be used:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace CustomConfigurationProvider
{
    public static class EntityFrameworkExtensions
    {
        public static IConfigurationBuilder AddEntityFrameworkConfig(
            this IConfigurationBuilder builder, Action<DbContextOptionsBuilder> setup)
        {
            return builder.Add(new EFConfigSource(setup));
        }
    }
}

下列程式碼示範如何使用自訂 EFConfigProviderThe following code shows how to use the custom EFConfigProvider:

using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using CustomConfigurationProvider;

public static class Program
{
    public static void Main()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        var connectionStringConfig = builder.Build();

        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            // Add "appsettings.json" to bootstrap EF config.
            .AddJsonFile("appsettings.json")
            // Add the EF configuration provider, which will override any
            // config made with the JSON provider.
            .AddEntityFrameworkConfig(options =>
                options.UseSqlServer(connectionStringConfig.GetConnectionString(
                    "DefaultConnection"))
            )
            .Build();

        Console.WriteLine("key1={0}", config["key1"]);
        Console.WriteLine("key2={0}", config["key2"]);
        Console.WriteLine("key3={0}", config["key3"]);
        Console.WriteLine();

        Console.WriteLine("Press a key...");
        Console.ReadKey();
    }
}

請注意,此範例會在 JSON 提供者後面新增自訂 EFConfigProvider,如此一來資料庫中的任何設定就會覆寫 appsettings.json 檔案中的設定。Note the sample adds the custom EFConfigProvider after the JSON provider, so any settings from the database will override settings from the appsettings.json file.

使用下列 appsettings.json 檔案:Using the following appsettings.json file:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CustomConfigurationProvider;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "key1": "value_from_json_1",
  "key2": "value_from_json_2",
  "key3": "value_from_json_3"
}

下列輸出隨即顯示:The following output is displayed:

key1=value_from_ef_1
key2=value_from_ef_2
key3=value_from_json_3

命令列組態提供者CommandLine configuration provider

命令列組態提供者會在執行階段接收組態的命令列引數索引鍵/值組。The CommandLine configuration provider receives command-line argument key-value pairs for configuration at runtime.

檢視或下載命令列組態範例View or download the CommandLine configuration sample

設定及使用命令列組態提供者Setup and use the CommandLine configuration provider

若要啟用命令列組態,請在 ConfigurationBuilder 的執行個體上呼叫 AddCommandLine 擴充方法:To activate command-line configuration, call the AddCommandLine extension method on an instance of ConfigurationBuilder:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;

public class Program
{
    public static IConfiguration Configuration { get; set; }

    public static void Main(string[] args = null)
    {
        var dict = new Dictionary<string, string>
            {
                {"Profile:MachineName", "MairaPC"},
                {"App:MainWindow:Left", "1980"}
            };

        var builder = new ConfigurationBuilder();

        builder.AddInMemoryCollection(dict)
            .AddCommandLine(args);

        Configuration = builder.Build();

        Console.WriteLine($"MachineName: {Configuration["Profile:MachineName"]}");
        Console.WriteLine($"Left: {Configuration["App:MainWindow:Left"]}");
        Console.WriteLine();

        Console.WriteLine("Press a key...");
        Console.ReadKey();
    }
}

執行程式碼,隨即顯示下列輸出:Running the code, the following output is displayed:

MachineName: MairaPC
Left: 1980

在命令列上傳遞引數索引鍵/值組會變更 Profile:MachineNameApp:MainWindow:Left 的值:Passing argument key-value pairs on the command line changes the values of Profile:MachineName and App:MainWindow:Left:

dotnet run Profile:MachineName=BartPC App:MainWindow:Left=1979

主控台視窗會顯示:The console window displays:

MachineName: BartPC
Left: 1979

若要使用命令列組態來覆寫其他組態提供者所提供的組態,請在 ConfigurationBuilder 上最後才呼叫 AddCommandLineTo override configuration provided by other configuration providers with command-line configuration, call AddCommandLine last on ConfigurationBuilder:

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

引數Arguments

在命令列上傳遞的引數必須符合下表所示的兩種格式之一:Arguments passed on the command line must conform to one of two formats shown in the following table:

引數格式Argument format 範例Example
單一引數:以等號 (=) 分隔的索引鍵/值組Single argument: a key-value pair separated by an equals sign (=) key1=value
連續兩個引數:以空格分隔的索引鍵/值組Sequence of two arguments: a key-value pair separated by a space /key1 value1

單一引數Single argument

值必須在等號 (=) 後面。The value must follow an equals sign (=). 這個值可以是 Null (例如 mykey=)。The value can be null (for example, mykey=).

索引鍵可能會有前置字元。The key may have a prefix.

索引鍵前置字元Key prefix 範例Example
沒有前置字元No prefix key1=value1
單虛線 (-)†Single dash (-)† -key2=value2
雙虛線 (--)Two dashes (--) --key3=value3
正斜線 (/)Forward slash (/) /key4=value4

†您必須在切換對應中提供具有單虛線前置字元 (-) 的索引鍵,如下所述。†A key with a single dash prefix (-) must be provided in switch mappings, described below.

範例命令:Example command:

dotnet run key1=value1 -key2=value2 --key3=value3 /key4=value4

注意:如果提供給組態提供者的切換對應中沒有 -key2,則會擲回 FormatExceptionNote: If -key2 isn't present in the switch mappings given to the configuration provider, a FormatException is thrown.

連續兩個引數Sequence of two arguments

值不可以是 Null,而且必須在以空格分隔的索引鍵後面。The value can't be null and must follow the key separated by a space.

索引鍵必須有前置字元。The key must have a prefix.

索引鍵前置字元Key prefix 範例Example
單虛線 (-)†Single dash (-)† -key1 value1
雙虛線 (--)Two dashes (--) --key2 value2
正斜線 (/)Forward slash (/) /key3 value3

†您必須在切換對應中提供具有單虛線前置字元 (-) 的索引鍵,如下所述。†A key with a single dash prefix (-) must be provided in switch mappings, described below.

範例命令:Example command:

dotnet run -key1 value1 --key2 value2 /key3 value3

注意:如果提供給組態提供者的切換對應中沒有 -key1,則會擲回 FormatExceptionNote: If -key1 isn't present in the switch mappings given to the configuration provider, a FormatException is thrown.

重複索引鍵Duplicate keys

如果提供了重複索引鍵,則會使用最後一個索引鍵/值組。If duplicate keys are provided, the last key-value pair is used.

切換對應Switch mappings

使用 ConfigurationBuilder 手動建置組態時,可以將參數對應字典到 AddCommandLine 方法。When manually building configuration with ConfigurationBuilder, a switch mappings dictionary can be added to the AddCommandLine method. 參數對應允許索引鍵名稱取代邏輯。Switch mappings allow key name replacement logic.

使用切換對應字典時,會檢查字典中是否有任何索引鍵符合命令列引數所提供的索引鍵。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 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.

在下列範例中,GetSwitchMappings 方法可讓命令列引數使用單虛線 (-) 索引鍵前置字元,並避免以子索引鍵前置字元開頭。In the following example, the GetSwitchMappings method allows command-line arguments to use a single dash (-) key prefix and avoid leading subkey prefixes.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;

public class Program
{
    public static IConfiguration Configuration { get; set; }

    public static Dictionary<string, string> GetSwitchMappings(
        IReadOnlyDictionary<string, string> configurationStrings)
    {
        return configurationStrings.Select(item =>
            new KeyValuePair<string, string>(
                "-" + item.Key.Substring(item.Key.LastIndexOf(':') + 1),
                item.Key))
                .ToDictionary(
                    item => item.Key, item => item.Value);
    }

    public static void Main(string[] args = null)
    {
        var dict = new Dictionary<string, string>
            {
                {"Profile:MachineName", "RickPC"},
                {"App:MainWindow:Left", "1980"}
            };

        var builder = new ConfigurationBuilder();

        builder.AddInMemoryCollection(dict)
            .AddCommandLine(args, GetSwitchMappings(dict));

        Configuration = builder.Build();

        Console.WriteLine($"MachineName: {Configuration["Profile:MachineName"]}");
        Console.WriteLine($"Left: {Configuration["App:MainWindow:Left"]}");
        Console.WriteLine();

        Console.WriteLine("Press a key...");
        Console.ReadKey();
    }
}

若未提供命令列引數,就會由提供給 AddInMemoryCollection 的字典來設定組態值。Without providing command-line arguments, the dictionary provided to AddInMemoryCollection sets the configuration values. 使用下列命令來執行應用程式:Run the app with the following command:

dotnet run

主控台視窗會顯示:The console window displays:

MachineName: RickPC
Left: 1980

使用下列命令在組態設定中傳遞:Use the following to pass in configuration settings:

dotnet run /Profile:MachineName=DahliaPC /App:MainWindow:Left=1984

主控台視窗會顯示:The console window displays:

MachineName: DahliaPC
Left: 1984

建立參數對應字典之後,其中會包含下表所示的資料:After the switch mappings dictionary is created, it contains the data shown in the following table:

KeyKey Value
-MachineName Profile:MachineName
-Left App:MainWindow:Left

若要示範如何使用字典切換索引鍵,請執行下列命令:To demonstrate key switching using the dictionary, run the following command:

dotnet run -MachineName=ChadPC -Left=1988

命令列索引鍵會互換。The command-line keys are swapped. 主控台視窗會顯示 Profile:MachineNameApp:MainWindow:Left 的組態值:The console window displays the configuration values for Profile:MachineName and App:MainWindow:Left:

MachineName: ChadPC
Left: 1988

web.config 檔案web.config file

當您在 IIS 或 IIS Express 中裝載應用程式時,需要 web.config 檔案。A web.config file is required when hosting the app in IIS or IIS Express. web.config 中的設定可讓 ASP.NET Core 模組啟動應用程式,並設定其他 IIS 設定和模組。Settings in web.config enable the ASP.NET Core Module to launch the app and configure other IIS settings and modules. 如果沒有 web.config 檔案,而專案檔包含 <Project Sdk="Microsoft.NET.Sdk.Web">,發行專案會在已發行的輸出 (publish 資料夾) 中建立 web.config 檔案。If the web.config file isn't present and the project file includes <Project Sdk="Microsoft.NET.Sdk.Web">, publishing the project creates a web.config file in the published output (the publish folder). 如需詳細資訊,請參閱在使用 IIS 的 Windows 上裝載 ASP.NET CoreFor more information, see Host ASP.NET Core on Windows with IIS.

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

若要在啟動期間存取 ConfigureServicesConfigure 內的組態,請參閱應用程式啟動主題中的範例。To access configuration within ConfigureServices or Configure during startup, see the examples in the Application startup topic.

從外部組件新增組態Adding 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. 如需詳細資訊,請參閱從外部組件增強應用程式For more information, see Enhance an app from an external assembly.

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

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

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

@page
@model IndexModel

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Index Page</title>
</head>
<body>
    <h1>Access configuration in a Razor Pages page</h1>
    <p>Configuration[&quot;key&quot;]: @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[&quot;key&quot;]: @Configuration["key"]</p>
</body>
</html>

其他備註Additional notes

  • 相依性插入 (DI) 會在叫用 ConfigureServices 之後才設定。Dependency Injection (DI) isn't set up until after ConfigureServices is invoked.
  • 組態系統無法感知 DI。The configuration system isn't DI aware.
  • IConfiguration 有兩個特製化:IConfiguration has two specializations:
    • IConfigurationRoot 用於根節點。IConfigurationRoot Used for the root node. 可觸發重新載入。Can trigger a reload.
    • IConfigurationSection 代表組態值區段。IConfigurationSection Represents a section of configuration values. GetSectionGetChildren 方法會傳回 IConfigurationSectionThe GetSection and GetChildren methods return an IConfigurationSection.
    • 在重新載入組態或存取各個提供者時使用 IConfigurationRootUse IConfigurationRoot when reloading configuration or for access to each provider. 以上皆為罕見案例。Neither of these situations are common.

其他資源Additional resources