翻譯 - ASP.NET Core 基本知識 - 配置(Configuration)


翻譯自 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0

ASP.NET Core 中的配置使用一個或者多個配置提供程(configuration providers)序實現。配置提供程序從多種鍵值對中的配置源中讀取配置數據:

  • 設置文件,例如 appsetting.json
  • 環境變量
  • Azure 鍵庫
  • Azure App 配置
  • 命令行參數
  • 自定義提供器,安裝的或者創建的
  • 目錄文件
  • 內存中的 .NET 對象

本話題提供 ASP.NET Core 中關於配置的信息。更多關於在控制台應用程序中使用配置的信息,查看 .NET Configuration.

默認配置

使用 dotnet new 或者 Visual Studio 創建的 ASP.NET Core web 應用程序生成以下代碼:

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 按照以下順序為應用程序提供默認配置:

  1. ChainedConfigurationProvider:添加一個現存的 IConfiguration 作為一個源。在一個默認配置例子中,添加主機(host)配置並且設置它作為第一個應用程序配置的源。
  2. appsettings.json 使用 JSON 配置提供器(JSON configuration provider)。
  3. appsetttings.Environment.json 使用 JSON 配置提供器(JSON configuration provider)。例如,appsettings.Production.json 和 appsettings.Developments.json。
  4. App secrets,當應用程序運行在開發 (Development) 環境中。
  5. 環境變量使用  Environment Variables configuration provider
  6. 命令行參數使用 Command-line configuration provider

后添加的配置提供器會覆蓋先前添加的鍵值設置。例如,如果 MyKey 同事在 appsettings.json 和 環境變量中設置,環境變量的值將會被使用。如果使用默認的配置提供器,命令行配置提供器(Command-line configuration provider) 將會覆蓋所有的提供器。

關於 CreateDefaultBuilder 的更多信息,查看 Default builder settings

下面的代碼展示了使能的配置提供器的添加順序:

public class Index2Model : PageModel
{
    private IConfigurationRoot ConfigRoot;

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

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

        return Content(str);
    }
}

appsettings.json

考慮下面的 appsettings.json 文件:

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

示例 (sample download) 中的代碼展示了幾個上面的配置設置:

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 按照以下順序加載配置:

1. appsettings.json

2. appsettings.Environment.json:例如,appsettings.Production.json 和 appsettings.Development.json 文件。文件的環境版本基於 IHostingEnvironment.EnvironmentName,更多信息,查看 Use multiple environments in ASP.NET Core.

appsettings.Environment.json 中的值會覆蓋 appsettings.json 中的值。例如,默認的:

  • 在開發環境中,appsettings.Development.json 配置會覆蓋 appsettings.json 中存在的值
  • 在生產環境中,appsettings.Production.json 的配置會覆蓋 appsettings.json 中存在的值,例如,當部署應用程序到 Azure 上的時候。

使用選項模型綁定繼承配置數據

讀取相關配置值的推薦方式是使用選項模型 (options pattern)。例如,讀取下面的配置值:

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

創建 PositionOptions 類:

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

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

一個選項類:

  • 必須是帶有公共無參數的構造方法的非抽象類
  • 所有公共的可讀寫的屬性類型要被綁定
  • 字段沒有綁定。在前面的代碼中,Position 沒有綁定。使用 Position 屬性,因此字符串 "Position" 就不用在綁定類到一個配置提供器的時候硬編碼在應用程序中

下面的代碼:

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 配置文件的改變也會被讀取到。

ConfigurationBinder.Get<T> 綁定和返回指定的類型。ConfigurationBinder.Get<T> 可能比使用 ConfigurationBinder.Bind 更方便。下面的代碼展示了如何使用 ConfigurationBinder.Get<T> 使用 PositionOptions 類:

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 配置文件的更改。

使用 options patter 的一種方法是綁定 Position 區域並且添加到依賴注入服務容器 (dependency injection service container) 中。下面的代碼中,PositionOptions 在 Configure 中被添加到服務容器中,並綁定到配置:

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

使用了上面的代碼,下面的代碼讀取 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 配置文件的更改。如果要讀取應用程序啟動后的更改,可以使用 IOptionsSnapshot

使用默認(default)的配置,appsettings.json 和 appsettings.Environment.json 文件使能了  reloadOnChange: true 。在應用程序啟動后對 appsettings.json 和 appsettings.Environment.json 的更改會被 JSON configuration provider 讀取到。

查看本文檔中 JSON configuration provider 關於添加更多 JSON 配置文件的信息。

合並服務集合

考慮下面的 ConfigureServices 方法,其中注冊服務和配置選項:

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

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

    services.AddRazorPages();
}

相關的一組的注冊可以被移動到擴展方法中去注冊服務。例如,配置服務被添加到下面的類中:

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

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

            return services;
        }
    }
}

其余的服務在一個相似的類中被注冊。下面的 ConfigureServices 方法使用的新的擴展方法注冊服務:

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

    services.AddRazorPages();
}

備注:每一個 services.Add{GROUP_NAME} 擴展方法添加和潛在的會配置服務。例如,AddControllersWithViews 添加帶有視圖的 MVC 控制器的服務,AddRazorPages 添加帶有 Razor Pages 的服務。我們推薦應用程序遵守命名的約定。把擴展方法統一放到命名空間 Microsoft.Extensions.DependencyInjection 中去封裝一組服務的注冊。

安全和用戶秘密

數據配置指導:

  • 永遠不要把密碼或者其他敏感數據使用配置提供器保存在代碼中或者保存在文本配置文件中。在開發過程中,可以使用 Secret Manager 工具保存秘密數據
  • 不要在開發環境或者測試環境中使用生產環境的秘密數據
  • 在工程外部指定秘密數據,以防被意外的提交到源代碼倉庫中

默認的,用戶秘密配置源是在 JSON 配置源之后注冊的。因此,用戶秘密的鍵值會生效,而不是 appsettings.json 和 appsettings.Environment.json 中的鍵值。

更多關於存儲密碼或者其他敏感數據的信息:

Azure Key Vault 為 ASP.NET Core 應用程序安全的存儲應用程序的秘密。更多信息查看 Azure Key Vault Configuration Provider in ASP.NET Core

環境變量

使用默認的配置,EnvironmentVariablesConfigurationProvider 在讀取 appsettings.json,appsettings.Environment.json,和 user secrets 之后從環境變量加載鍵值對。因此,從環境變量讀取到的鍵值會覆蓋從 appsettings.json, appsettings.Environment.json 和 user secrets 中讀取到的值。

: 分隔符在所有平台上對於環境便令分級鍵都是不工作的。__ 雙下換線:

  • 所有平台都支持。例如, Bash 不支持 : 分隔符,但是支持 __
  • 會自動的被一個 : 替換

下面的設置命令:

  • 在 Windows 上設置前面示例(preceding exampl)中的環境鍵值和值
  • 使用示例程序(sample download)測試設置。dotnet run 命令必須在工程目錄中運行
set MyKey="My key from Environment"
set Position__Title=Environment_Editor
set Position__Name=Environment_Rick
dotnet run

上面的環境變量設置:

  • 僅僅在設置他們的命令行窗口中啟動的進程中
  • 不會被使用 Visual Studio 啟動的瀏覽器讀取

下面的  setx 命令可以被用來在 Windows 上設置環境鍵和值。不同於 set,setx 是持久化的。/M 在系統環境設置變量。如果沒有使用 /M 開關,一個用戶的環境變量會被設置。

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

為了測試上面的命令會覆蓋 appsettings.json 和 asppsettings.Environment.json 的配置,需要做以下操作:

  • 使用 Visual Studio: 退出和重啟 Visual Studio
  • 使用命令行:啟動一個新的命令窗口,輸入 dotnet run

調用 AddEnvironmentVariables,使用一個字符串指定環境變量的前綴:

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

在上面的代碼中:

當配置鍵值對被讀取的時候,前綴會被去除。

下面的命令測試自定義前綴:

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

默認配置 (default configuration) 加載帶有前綴為 DOTNET_ 和 ASPNETCORE_ 的環境變量和命令行參數。DOTNET_ 和 ASPNETCORE_ 前綴被 ASP.NET Core 用來配置主機和應用程序配置 (host and app configuration),不能用來作為用戶配置。更多關於主機和應用程序的配置,查看 .NET Generic Host

關於  Azure App Service,在設置 (Settings) > 配置 (Configuration) 頁面選擇 新建應用程序設置 (New application setting)。Azure 應用程序服務設置:

  • 在休息是加密,並通過加密通道傳輸
  • 暴露為環境變量

更多信息,查看 Azure Apps: Override app configuration using the Azure Portal

查看 Connection string prefixes 了解關於 Azure 數據庫連接字符串的信息。

 環境變量命名

環境變量的命名反映了 appsettings.json 文件的結構。層級中的每一個元素使用雙下划線(推薦的)或者冒號分割開來。當一個元素的結構包含一個數組的時候,數組的索引應該被當做是當前路徑中的一個額外的元素名稱。考慮下面的 appsettings.json 文件和它在環境變量中等價的值。

appsettings.json

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

環境變量 (environment variables)

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

生成的 launchSettings.json 文件中環境變量的設置

在 launchSettings.json 中設置的環境變量會覆蓋那些在系統環境中設置的值。例如,ASP.NET Core web 模板會生成一個 lauchSettings.json 文件,文件中設置了

endpoint 配置:

"applicationUrl": "https://localhost:5001;http://localhost:5000"

對 applicationUrl 的配置設置環境變量 ASPNETCORE_URLS  並覆蓋環境中的值。

Escape environment variables on Linux

在 linux 上,URL 環境變量的值必須被 escape 后系統才能夠解析它。使用 linux systemd-escape 工具生成 http:--localhost:5001

groot@terminus:~$ systemd-escape http://localhost:5001
http:--localhost:5001

顯示環境變量

下面的代碼在應用程序啟動的時候輸出顯示了環境變量和對應的值,在調試環境設置的時候非常有用:

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    var config = host.Services.GetRequiredService<IConfiguration>();

    foreach (var c in config.AsEnumerable())
    {
        Console.WriteLine(c.Key + " = " + c.Value);
    }
    host.Run();
}

命令行

使用默認的配置,CommandLineConfigurationProvider 在下列配置源之后從命令行參數鍵值對中加載配置:

  • appsettings.json 和 appsettings.Environment.json 文件
  • 開發環境中的 App secrets
  • 環境變量

默認的,在命令行中配置的值會覆蓋其它所有配置提供的值。

命令行參數

下面的命令使用 = 設置鍵和值:

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

下面的命令使用 / 設置鍵值:

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

下面的命令使用 -- 設置鍵值:

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

鍵值:

  • 必須緊跟 = ,或當值在一個空格后面的時候,鍵必須有個 -- 或者 / 前綴
  • 當使用 = 的時候,值不是必須要有的,例如 MySetting=

在相同的命令行中,不要把使用 = 的鍵值對和使用空格的鍵值對的命令行參數混淆。

轉換映射

切換映射允許鍵名替換邏輯。可以給 AddCommandLine 方法提供一個切換替換的字典。

當切換映射字典被用到的時候,字典被用來檢查匹配命令行參數提供的鍵。日過命令行的鍵在字典中被找到,字典中的值就會被傳回用來設置應用程序配置的鍵值對。切換映射要求任何的命令行鍵使用一個單獨的破折號作為前綴。

切換映射字典鍵的規則:

  • 切換必須以 - 或者 -- 開頭
  • 切換映射字典不能包含重復的鍵

 

使用一個切換映射字典,需要把它傳遞給 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>();
            });
    }
}

下面的代碼展示了被替換的鍵的值:

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"]}'");
    }
}

下面的命令用來測試鍵替換:

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

對於使用切換映射的應用程序,調用 CreateDefaultBuilder 不應該傳遞參數。CreateDefaultBuilder 方法的 AddCommandLine 的調用不包括映射切換,沒有方法可以傳遞切換映射的字典給 CreateDefaultBuilder。解決方法是允許 ConfigurationBuilder 方法的 AddCommandLine 同時處理參數和切換映射字典而不是傳遞參數給 CreateDefaultBuilder。

分層配置數據

配置 API 通過使用在配置鍵中的分界符扁平化分層數據來讀取配置數據。

示例程序 (sample download) 包含下面的 appsettings.json 文件:

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

下面示例 (sample download) 中的代碼展示了一些配置設置:

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

讀取分層配置數據的首選方式是使用選項模型。更多信息,查看本文檔中的綁定分層配置數據 (Bind hierarchical configuration data)。

GetSection 和 GetChildren 方法可以用來分離配置數據中的分區和分區中的子部分。這些方法在之后的 GetSection, GetChildren, and Exists 中會描述到。

配置的鍵和值

配置的鍵:

  • 不區分大小寫。例如 ConnectionString 和 connectionstring 被認為是等價的鍵
  • 如果一個鍵和值在多個配置提供器中被設置,最后一個提供器的值將會被使用。更多信息,查看默認配置 (Default configuration)
  • 分層鍵
    - 在配置 API 內部,一個冒號分隔符 (:) 在所有平台都能工作
    - 在環境變量中,一個冒號分隔符可能不會在所有平台上工作。雙下划線 (__) 被所有平台支持,並且會被自動的轉換為一個冒號 (:)
    - 在 Azure 鍵倉庫中,分層的鍵使用 -- 作為一個分隔符。當秘密數據被加載到應用程序配置的時候,Azure Key Vault configuration provider 自動使用一個冒號 (:) 替換 (--)。
  • ConfigurationBinder 支持綁定數組到在配置鍵中使用數組索引的對象。數組綁定在 Bind an array to a class 部分描述。

配置值:

  • 是字符串
  • Null 值不能存儲在配置中或者綁定到對象

配置提供器

下面的表格中顯示了 ASP.NET Core 應用程序中可以使用的配置提供器

Provider Providers configuration from
Azure Key Vault configuration provider Azure Key Valut
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,XML 文件
Key-per-file configuration provider 字典文件
Memory configuration provider 內存中的集合
User secrets 用戶配置目錄中的文件

配置源的讀取的順序按照它們的配置提供器被指定的順序。在代碼中對配置提供器排序來滿足應用程序要求的配置源的順序。

一個典型的配置提供器的順序是:

  1. appsettings.json
  2. appsettings.Environment.json
  3. User secrets
  4. 使用 Environment Variables configuration provider 的環境變量
  5. 使用 Command-line configuration provider 的命令行參數

一個常用的實踐是在一系列的配置提供器的最后添加命令行配置提供器,用來覆蓋其它提供器的配置設置

上面的提供器的順序在默認配置 (default configuration) 中使用。

連接字符串前綴

配置 API 對於四種連接字符串環境變量有特殊的處理規則。這些連接字符串會根據應用程序環境解析來配置 Azure 連接字符串。下面表格中的帶有前綴的環境變量在應用程序使用默認配置 (default configuration)或者沒有前綴沒有應用到 AddEnvironmentVariables 的情況下會被加載到應用程序中。

Connection string prefix Provider
CUSTOMCONNSTR_ 自定義提供器
MYSQLCONNSTR_ MySQL
SQLAZURECONNSTR_ Azure SQL Database
SQLCONNSTR_ SQL Server

當一個環境變量被發現並且使用表格中四種前綴的任一種被加載到配置中的時候:

  • 通過移除環境變量的前綴創建配置的鍵,添加一個配置鍵的區域(ConnectionStrings)
  • 一個新的配置的鍵值對被創建,這個鍵值對代表了數據庫連接提供器 (CUSTOMCONNSTR_ 除外,由於沒有固定的提供器)
環境變量鍵 轉換后的配置鍵 提供器配置入口
CUSTOMCONNSTR_{KEY} ConnectionStrings:{KEY} 配置入口沒有創建
MYSQLCONNSTR_{KEY} ConnectionString:{KEY}

Key:ConnectionStrings:

{KEY}_ProviderName:

Value:MySql.DataMySqlClient

SQLAZURECONNSTR_{KEY} ConnectionStrings:{KEY}

Key:ConnectionStrings:

{KEY}_ProviderName:

Value:System.Data.SqlClient

SQLCONNSTR_{KEY} ConnectionStrings:{KEY}

Key:ConnectionStrings:

{KEY}_ProviderName:

Value:System.Data.SqlClient

 文件配置提供器

FileConfigurationProvider 是從文件系統加載配置的基類。下面的配置提供器都從 FileConfigurationProvider 類繼承而來。

INI 配置提供器

IniConfigurationProvider 在運行時從 INI 文件中加載鍵值對的配置。

下面的代碼清空了所有配置提供器,添加了一些配置提供器:

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

 在上面的代碼中,文件 MyIniCofig.ini 和 MyIniConfig.Environment.ini 中的配置會被以下配置覆蓋:

示例程序(sample download)包含以下 MyIniConfig.ini 文件:

MyKey="MyIniConfig.ini Value"

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

[Logging:LogLevel]
Default=Information
Microsoft=Warning

下面的代碼來自示例程序(sample download),展示了前面配置設置:

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

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

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


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

JSON 配置提供器

JsonConfigurationProvider 從 JSON 文件中加載鍵值對

重載可以指定:

  • 文件是否可選
  • 文件改變配置是否重新加載

考慮下面的代碼:

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

上面的代碼:

一般的,你並不希望一個自定義的 JSON 文件去覆蓋 Environment variables configuration provider 和 Command-line configuration provider 中的配置設置值。

下面的代碼清除了所有的配置提供器並且添加了一些配置提供器:

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.json 和 MyConfig.Environment.json 文件中的設置:

示例程序(sample download)包含以下 MyConfig.json 文件:

{
  "Position": {
    "Title": "My Config title",
    "Name": "My Config Smith"
  },
  "MyKey":  "MyConfig.json Value",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

下面的示例程序(sample download)中的代碼展示了上面配置設置:

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 配置提供器

XmlConfigurationProvider 在運行時從 XML 文件中加載鍵值對配置。

下面的代碼清空了所有的配置提供器並且添加了一些配置提供器:

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

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

                var env = hostingContext.HostingEnvironment;

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

                config.AddEnvironmentVariables();

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

在上面的代碼中,MyXMLFile.xml 和 MyXMLFile.Environment.xml 文件中的設置會被以下配置中的設置覆蓋:

示例程序(sample download)包含下面的 MyXMLFile.xml 文件:

<?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>

下面示例程序(sample download)中的代碼展示了一些上面配置設置:

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 屬性用來區分的話,也是可以工作的:

<?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>

下面的配置讀取前面的配置文件,展示了鍵和值:

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

屬性可以用來提供值:

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

前面的配置文件使用下面的鍵和值加載:

  • key: attribute
  • section: key:attribute

Key-per-file 配置提供器

KeyPerFileConfigurationProvider 使用目錄文件作為鍵值對配置。文件名稱作為鍵。文件的內容作為值。Key-per-file 配置提供器在 Docker 托管的場景中使用。

為了啟動 key-per-file 配置,可以調用 ConfigurationBuilder 實例的擴展方法 AddKeyPerFile。文件的 directoryPath 必須是絕對路徑。

重載允許指定:

  • 使用 Action<KeyPerFileConfigurationSource> 代理來配置源
  • 目錄和目錄的路徑是否可選

雙下划線(__)用來在文件名中作為配置鍵的分隔符。例如,文件名 Loggin_LogLevel_System 會生成配置鍵 Logging:LogLevel:System。

在創建主機的時候調用 ConfigureAppConfiguration 來指定應用程序配置:

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

內存配置提供器

MemoryConfigurationProvider 使用內存中的集合作為配置鍵值對。

下面的代碼添加一個內存集合到配置系統:

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

下面示例程序(sample download)中的代碼展示了前面添加的配置中的設置:

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) 在默認配置提供器(default configuration providers)之后添加。配置提供器的加載順序的示例,請查看  JSON configuration provider

查看 Bind an array 另一個使用 MemoryConfigurationProvider 的例子。

Kestrel endpoint 配置

Kestrel 指定的 endpoint 配置會覆蓋所有 cross-server endpoint 的配置。Cross-server endpoint 配置包含:

考慮下面在 ASP.NET Core web 應用程序中使用的 appsetting.json 文件:

{
  "Kestrel": {
    "Endpoints": {
      "Https": {
        "Url": "https://localhost:9999"
      }
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

當前面高亮標記的配置在 ASP.NET Core web 應用程序中被使用,並且應用程序使用下面的 cross-server endpoint 配置在命令行中啟動:

dotnet run --urls="https://localhost:7777"

Kestrel 會綁定到 appsettings.json 文件中的 endpoint 特定的的配置(https://localhost:9999),而不是 https://localhost:7777。

考慮指定 Kestrel enpoint 配置作為一個環境變量:

set Kestrel__Endpoints__Https__Url=https://localhost:8888

在上面這個環境變量中,Https 是 Kestrel 指定的 endpoint 的名稱。前面的 appsettings.json 文件也定義了指定的 endpoint 名稱 Https. 默認的,使用 Environment Variables configuration provider 的環境變量在 appsettings.Environment.json 之后被讀取,因此,上面的環境變量被用作 Https endpoint。

 

GetValue

ConfigurationBinder.GetValue<T> 使用指定的鍵從配置文件中獲取一個單獨的值,並轉換為指定類型:

public class TestNumModel : PageModel
{
    private readonly IConfiguration Configuration;

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

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

在上面的代碼中,如果 NumberKey 在配置中沒有被發現,默認值 99 將會被使用。

GetSection, GetChildren,and Exists

下面的示例中,考慮以下 MySubsection.json 文件:

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

下面的代碼添加 MySubsection.json 到配置提供器中:

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

GetSection

IConfiguration.GetSection 使用一個子區域鍵返回一個配置子區域:

下面的代碼返回 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: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 從不返回 null。如果沒有匹配的區域,一個空的 IConfigurationSection 被返回。

當 GetSection 返回一個匹配的區域,值(Value)不會被填充。當一個區域存在的時候,會返回一個鍵(Key)和路徑(Path)。

GetChildren 和 Exists

下面的代碼調用 IConfiguration.GetChildren,並返回 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);
    }
}

上面的代碼調用 ConfigurationExtensions.Exists 驗證指定區域是否存在。

綁定一個數組

ConfigurationBinder.Bind 支持使用配置中鍵中的數組索引綁定數組到一組對象。任何暴露一個數字類型鍵的段格式的數組,都是能夠綁定到一個 POCO 類的數組。

考慮來自示例程序(sample download)中的 MyArray.json 文件:

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

下面的代碼添加 MyArray.json 文件到配置提供器中:

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

下面的代碼讀取配置並且顯示出配置中的值:

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

上面的代碼輸出下面的內容:

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

上面的輸出中,索引 3 對應的值是 value40,和文件 MyArray.json 中的 “4”:"value40" 相對應。綁定數組的索引是連續的,而不是綁定到配置鍵的值作為索引。配置綁定沒有綁定空值或者為綁定對象創建空值的能力。

下面的代碼使用 AddInMemoryCollection 擴展方法加載 array:entries 配置:

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 中的配置並且顯示輸出對應的值:

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

上面的代碼輸出以下內容:

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

索引 #3 的綁定對象對應的配置數據是鍵 array:4 以及它對應的值。當包含一個數組的配置數據被綁定時,配置鍵對應的數組索引在創建對象時被用來迭代配置數據。配置數據不能引用一個空值,並且當一個數組在配置鍵跳過一個或者多個索引的時候,一個空的實體是不能被創建的。

缺失的索引為 #3 的配置項目可以在綁定到 ArrayExample 實例之前通過任意的配置提供器讀取索引 $3 鍵值對來提供。

考慮示例程序中的 Value3.json 文件:

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

下面的代碼包含 Value3.json 的配置和 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>();
            });
    }
}

下面的代碼讀取前面的配置並且顯示配置值:

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

上面的代碼輸出以下內容:

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

自定義配置提供器不需要實現數組綁定。

自定義配置提供器

示例程序展示了如何創建一個基本的配置提供器,使用 Entity Framework (EF) 從數據庫中讀取鍵值對配置。

提供器有以下特性:

  • EF 內存數據庫僅僅用於展示目的。如果要使用需要連接字符串的數據庫,可以實現一個次要的 ConfigurationBuilder 支持來自其它配置提供器的連接字符串
  • 提供器在啟動時讀取一個數據庫的表到配置中。提供器獲取數據庫不基於基本的 per-key
  • Reload-on-change 沒有實現,因此在應用程序啟動后更新數據庫對應用程序的配置沒有影響

定義一個 EFConfigurationValue 實體用來存儲數據庫中的配置值。

Models/EFConfigurationValue.cs:

 

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

添加一個 EFConfigurationContext 用來存儲和訪問配置值。

EFConfigurationProvider/EFConfigurationContext.cs:

// using Microsoft.EntityFrameworkCore;

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

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

創建一個實現 IConfigurationSource 接口的類:

EFConfigurationProvider/EFConfigurationSource.cs:

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

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

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

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

通過繼承 ConfigurationProvider 創建一個自定義的配置提供器。配置提供器初始化一個空的數據庫。由於 configuration keys are case-insensitive 的原因,

使用 case-insensitive 的比較器(StringComparer.OrdinalIgnoreCase)創建的字典被用來初始化數據庫。

EFConfigurationProvider/EFConfigurationProvider.cs:

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

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

    Action<DbContextOptionsBuilder> OptionsAction { get; }

    public override void Load()
    {
        var builder = new DbContextOptionsBuilder<EFConfigurationContext>();

        OptionsAction(builder);

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

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

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

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

        dbContext.SaveChanges();

        return configValues;
    }
}

AddEFConfiguration 的一個擴展方法允許添加配置源到 ConfigurationBuilder.

Extension/EntityFrameworkExtensions.cs:

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

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

下面的代碼展示了在 Program.cs 中如何使用 EFConfigurationProvider:

// using Microsoft.EntityFrameworkCore;

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

在 Startup 中獲取配置

下面的代碼在 Startup 的方法中顯示了配置數據:

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

使用 startup 約定的方法獲取配置的示例,請查看 App startup: Convenience methods

在 Razor Pages 中獲取配置

下面的代碼在 Razor Page 中顯示配置:

 

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

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

在下面的代碼中,使用了 Configure 方法把 MyOptions 添加到服務容器中,並且綁定到配置:

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

    services.AddRazorPages();
}

下面的代碼使用 @inject Razor directive 指令獲取和顯示選項的值:

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


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

在 MVC view 文件中獲取配置

下面的代碼在一個 MVC view 中展示配置數據:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

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

使用代理配置選項

代理中的選項配置會覆蓋配置提供器中的值。

使用代理配置選項在示例程序中作為 Example 2 展示。

在下面的代碼中,IConfigureOptions<TOptions> 服務被添加到服務容器中。它使用一個代理配置 MyOptions 的值:

 

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

    services.AddRazorPages();
}

下面的代碼展示了選項的值:

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 的值在 appsetting.json 指定,然后會被配置代理覆蓋。

主機與應用配置

在應用程序配置和啟動前,一個主機被配置和啟動。主機負責應用程序的啟動和生命周期的管理。應用程序和主機都是使用本文中描述的配置提供器配置。主機配置的鍵值對也包含在應用程序配置中。更多關於當主機創建的時候如果使用配置提供器以及不同配置源如何影響主機配置,請查看 ASP.NET Core fundamentals

默認主機配置

更多關於使用 Web Host 時的默認配置的細節,查看 ASP.NET Core 2.2 version of this topic

  • 主機配置
    前綴為 DOTNET_(例如 DOTNET_ENVIRONMENT) 的環境變量使用 Environment Variables configuration provider。當配置鍵值對被加載的時候,前綴 (DOTNET_) 會被去除。
    命令行參數使用 Command-line configuration provider
  • Web 主機的建立(ConfigureWebHostDefaults)
    Kestrel 被用來作為 web 服務器,使用應用程序配置提供器
    添加主機過濾中間件
    如果 ASPNETCORE_FORWARDEDHEADERS_ENABLED 環境變量設置為 true 時,添加 Forwarded Headers Middleware 中間件
  • 使能 IIS 集成

其它配置

本文只和 app configuration 有關。其它運行和托管 ASP.NET Core 應用程序方面的配置文件並不涵蓋:

launchSettings.json 中的環境變量設置會覆蓋系統中的環境變量。

更過關於從更早版本 ASP.NET Core 遷移應用程序配置文件的信息,請查看 Migrate from ASP.NET to ASP.NET Core

從外部程序集添加配置

一個 IHostingStartup 的實現允許在 startup 中從一個外部的程序集的 Startup 類的外部添加更多的配置到一個應用程序中。更多信息請查看 Use hosting startup assemblies in ASP.NET Core


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM