Konstruktory konfiguracji dla platformy ASP.NETConfiguration builders for ASP.NET
Autorzy Stephen Molloy i Rick AndersonBy Stephen Molloy and Rick Anderson
Konstruktory konfiguracji zapewniają nowoczesne i Agile mechanizm dla aplikacji ASP.NET, aby uzyskać wartości konfiguracyjne ze źródeł zewnętrznych.Configuration builders provide a modern and agile mechanism for ASP.NET apps to get configuration values from external sources.
Konstruktory konfiguracji:Configuration builders:
- Są dostępne w .NET Framework 4.7.1 i nowszych.Are available in .NET Framework 4.7.1 and later.
- Zapewnianie elastycznego mechanizmu odczytywania wartości konfiguracyjnych.Provide a flexible mechanism for reading configuration values.
- Należy zająć się niektórymi podstawowymi potrzebami aplikacji, które są przenoszone do kontenera i środowiska ukierunkowanego na chmurę.Address some of the basic needs of apps as they move into a container and cloud focused environment.
- Może służyć do ulepszania ochrony danych konfiguracji przez rysowanie ze źródeł, które były wcześniej niedostępne (na przykład Azure Key Vault i zmienne środowiskowe) w systemie konfiguracji .NET.Can be used to improve protection of configuration data by drawing from sources previously unavailable (for example, Azure Key Vault and environment variables) in the .NET configuration system.
Konstruktory konfiguracji klucza/wartościKey/value configuration builders
Typowym scenariuszem, który może być obsługiwany przez konstruktory konfiguracji, jest zapewnienie podstawowego mechanizmu wymiany klucza/wartości dla sekcji konfiguracyjnych, które są zgodne ze wzorcem klucz/wartość.A common scenario that can be handled by configuration builders is to provide a basic key/value replacement mechanism for configuration sections that follow a key/value pattern. Koncepcja .NET Framework ConfigurationBuilders nie jest ograniczona do określonych sekcji konfiguracyjnych ani wzorców.The .NET Framework concept of ConfigurationBuilders is not limited to specific configuration sections or patterns. Jednak wiele konstruktorów konfiguracji w programie Microsoft.Configuration.ConfigurationBuilders
(GitHub, NuGet) pracuje w obrębie wzorca klucz/wartość.However, many of the configuration builders in Microsoft.Configuration.ConfigurationBuilders
(github, NuGet) work within the key/value pattern.
Ustawienia konstruktorów konfiguracji klucza/wartościKey/value configuration builders settings
Następujące ustawienia mają zastosowanie do wszystkich konstruktorów konfiguracji klucza/wartości w programie Microsoft.Configuration.ConfigurationBuilders
.The following settings apply to all key/value configuration builders in Microsoft.Configuration.ConfigurationBuilders
.
TrybMode
Konstruktory konfiguracji używają zewnętrznego źródła informacji o klucz/wartość, aby wypełnić wybrane elementy klucza/wartości systemu konfiguracyjnego.The configuration builders use an external source of key/value information to populate selected key/value elements of the configuration system. W <appSettings/>
<connectionStrings/>
poszczególnych sekcjach i są uzyskiwane specjalne podejście od konstruktorów konfiguracji.Specifically, the <appSettings/>
and <connectionStrings/>
sections receive special treatment from the configuration builders. Konstruktorzy pracują w trzech trybach:The builders work in three modes:
Strict
— Tryb domyślny.Strict
- The default mode. W tym trybie Konstruktor konfiguracji działa tylko w przypadku dobrze znanych sekcji konfiguracji klucz/wartość.In this mode, the configuration builder only operates on well-known key/value-centric configuration sections.Strict
Tryb wylicza każdy klucz w sekcji.Strict
mode enumerates each key in the section. Jeśli w źródle zewnętrznym zostanie znaleziony pasujący klucz:If a matching key is found in the external source:- Konstruktory konfiguracji zastępują wartość w sekcji konfiguracji w wyniku wartością z zewnętrznego źródła.The configuration builders replace the value in the resulting configuration section with the value from the external source.
Greedy
— Ten tryb jest ściśle powiązany zStrict
trybem.Greedy
- This mode is closely related toStrict
mode. Zamiast ograniczać się do kluczy, które już istnieją w oryginalnej konfiguracji:Rather than being limited to keys that already exist in the original configuration:- Konstruktory konfiguracji dodaje wszystkie pary klucz/wartość ze źródła zewnętrznego do sekcji konfiguracji w wyniku.The configuration builders adds all key/value pairs from the external source into the resulting configuration section.
Expand
-Działa na nieprzetworzonym kodzie XML przed przeanalizowaniem go do obiektu sekcji konfiguracji.Expand
- Operates on the raw XML before it's parsed into a configuration section object. Można go traktować jako rozszerzenie tokenów w ciągu.It can be thought of as an expansion of tokens in a string. Każda część nieprzetworzonego ciągu XML zgodna ze wzorcem${token}
jest kandydatem do rozwinięcia tokenu.Any part of the raw XML string that matches the pattern${token}
is a candidate for token expansion. Jeśli w zewnętrznym źródle nie zostanie znaleziona odpowiednia wartość, token nie zostanie zmieniony.If no corresponding value is found in the external source, then the token is not changed. Konstruktory w tym trybie nie są ograniczone do<appSettings/>
sekcji i<connectionStrings/>
.Builders in this mode are not limited to the<appSettings/>
and<connectionStrings/>
sections.
Następujące znaczniki z web.config umożliwiają EnvironmentConfigBuilder w Strict
trybie:The following markup from web.config enables the EnvironmentConfigBuilder in Strict
mode:
<configuration>
<configSections>
<section name="configBuilders"
type="System.Configuration.ConfigurationBuildersSection,
System.Configuration, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="MyEnvironment"
type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Environment,
Version=1.0.0.0, Culture=neutral" />
</builders>
</configBuilders>
<appSettings configBuilders="MyEnvironment">
<add key="ServiceID" value="ServiceID value from web.config" />
<add key="ServiceKey" value="ServiceKey value from web.config" />
</appSettings>
<connectionStrings configBuilders="MyEnvironment">
<add name="default" connectionString="Data Source=web.config/mydb.db" />
</connectionStrings>
Poniższy kod odczytuje <appSettings/>
i <connectionStrings/>
pokazano w poprzednim pliku web.config :The following code reads the <appSettings/>
and <connectionStrings/>
shown in the preceding web.config file:
using System;
using System.Configuration;
using System.Web.UI;
namespace MyConfigBuilders
{
public partial class About : Page
{
public string ServiceID { get; set; }
public string ServiceKey { get; set; }
public string ConString { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
ServiceID = ConfigurationManager.AppSettings["ServiceID"];
ServiceKey = ConfigurationManager.AppSettings["ServiceKey"];
ConString = ConfigurationManager.ConnectionStrings["default"]
?.ConnectionString;
}
}
}
Poprzedni kod ustawi wartości właściwości na:The preceding code will set the property values to:
- Wartości w pliku web.config , jeśli klucze nie są ustawione w zmiennych środowiskowych.The values in the web.config file if the keys are not set in environment variables.
- Wartości zmiennej środowiskowej, jeśli jest ustawiona.The values of the environment variable, if set.
Na przykład ServiceID
będzie zawierać:For example, ServiceID
will contain:
- "ServiceID wartość z web.config", jeśli zmienna środowiskowa
ServiceID
nie została ustawiona."ServiceID value from web.config", if the environment variableServiceID
is not set. - Wartość
ServiceID
zmiennej środowiskowej, jeśli jest ustawiona.The value of theServiceID
environment variable, if set.
Na poniższej ilustracji przedstawiono <appSettings/>
klucze/wartości z poprzedniego web.config zestawu plików w edytorze środowiska:The following image shows the <appSettings/>
keys/values from the preceding web.config file set in the environment editor:
Uwaga: aby zobaczyć zmiany w zmiennych środowiskowych, może być konieczne zamknięcie i ponowne uruchomienie programu Visual Studio.Note: You might need to exit and restart Visual Studio to see changes in environment variables.
Obsługa prefiksówPrefix handling
Prefiksy kluczy mogą uprościć ustawienie kluczy, ponieważ:Key prefixes can simplify setting keys because:
- Konfiguracja .NET Framework jest złożona i zagnieżdżona.The .NET Framework configuration is complex and nested.
- Zewnętrzne źródła kluczy/wartości są zwykle podstawowe i płaskie według natury.External key/value sources are commonly basic and flat by nature. Na przykład zmienne środowiskowe nie są zagnieżdżone.For example, environment variables are not nested.
Użyj dowolnych z poniższych metod, aby wprowadzić zarówno <appSettings/>
, jak i <connectionStrings/>
do konfiguracji za pomocą zmiennych środowiskowych:Use any of the following approaches to inject both <appSettings/>
and <connectionStrings/>
into the configuration via environment variables:
- Z
EnvironmentConfigBuilder
wStrict
trybie domyślnym i odpowiednimi nazwami kluczy w pliku konfiguracji.With theEnvironmentConfigBuilder
in the defaultStrict
mode and the appropriate key names in the configuration file. Powyższy kod i znacznik przyjmuje takie podejście.The preceding code and markup takes this approach. Korzystając z tej metody, nie można mieć identycznie nazwanych kluczy w obu<appSettings/>
i<connectionStrings/>
.Using this approach you can not have identically named keys in both<appSettings/>
and<connectionStrings/>
. - Użyj dwóch
EnvironmentConfigBuilder
trybów wGreedy
trybie z prefiksami DISTINCT istripPrefix
.Use twoEnvironmentConfigBuilder
s inGreedy
mode with distinct prefixes andstripPrefix
. Dzięki temu aplikacja może odczytywać<appSettings/>
i<connectionStrings/>
bez konieczności aktualizować pliku konfiguracji.With this approach, the app can read<appSettings/>
and<connectionStrings/>
without needing to update the configuration file. W następnej sekcji stripPrefix, pokazano, jak to zrobić.The next section, stripPrefix, shows how to do this. - Użyj dwóch
EnvironmentConfigBuilder
trybów wGreedy
trybie z różnymi prefiksami.Use twoEnvironmentConfigBuilder
s inGreedy
mode with distinct prefixes. W tym podejściu nie można mieć zduplikowanych nazw kluczy, ponieważ nazwy kluczy muszą się różnić prefiksami.With this approach you can't have duplicate key names as key names must differ by prefix. Na przykład:For example:
<configuration>
<configSections>
<section name="configBuilders"
type="System.Configuration.ConfigurationBuildersSection,
System.Configuration, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="AS_Environment" mode="Greedy" prefix="AppSetting_"
type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Environment" />
<add name="CS_Environment" mode="Greedy" prefix="ConnStr_"
type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Environment" />
</builders>
</configBuilders>
<appSettings configBuilders="AS_Environment">
<add key="AppSetting_ServiceID" value="ServiceID value from web.config" />
<add key="AppSetting_default" value="AppSetting_default value from web.config" />
</appSettings>
<connectionStrings configBuilders="CS_Environment">
<add name="ConnStr_default" connectionString="Data Source=web.config/mydb.db" />
</connectionStrings>
Przy poprzedzającym znaczniku można użyć tego samego prostego źródła klucza/wartości, aby wypełnić konfigurację dla dwóch różnych sekcji.With the preceding markup, the same flat key/value source can be used to populate configuration for two different sections.
Na poniższej ilustracji przedstawiono <appSettings/>
i <connectionStrings/>
klucze/wartości z poprzedniego web.config zestawu plików w edytorze środowiska:The following image shows the <appSettings/>
and <connectionStrings/>
keys/values from the preceding web.config file set in the environment editor:
Poniższy kod odczytuje <appSettings/>
<connectionStrings/>
klucze i/wartości zawarte w poprzednim pliku web.config :The following code reads the <appSettings/>
and <connectionStrings/>
keys/values contained in the preceding web.config file:
public partial class Contact : Page
{
public string ServiceID { get; set; }
public string AppSetting_default { get; set; }
public string ConString { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
ServiceID = ConfigurationManager.AppSettings["AppSetting_ServiceID"];
AppSetting_default = ConfigurationManager.AppSettings["AppSetting_default"];
ConString = ConfigurationManager.ConnectionStrings["ConnStr_default"]
?.ConnectionString;
}
}
Poprzedni kod ustawi wartości właściwości na:The preceding code will set the property values to:
- Wartości w pliku web.config , jeśli klucze nie są ustawione w zmiennych środowiskowych.The values in the web.config file if the keys are not set in environment variables.
- Wartości zmiennej środowiskowej, jeśli jest ustawiona.The values of the environment variable, if set.
Na przykład przy użyciu poprzedniego pliku web.config , klucze/wartości w poprzednim obrazie edytora środowiska i Poprzedni kod są ustawione następujące wartości:For example, using the previous web.config file, the keys/values in the previous environment editor image, and the previous code, the following values are set:
KluczKey | WartośćValue |
---|---|
AppSetting_ServiceIDAppSetting_ServiceID | AppSetting_ServiceID ze zmiennych ENVAppSetting_ServiceID from env variables |
AppSetting_defaultAppSetting_default | AppSetting_default wartość z ENVAppSetting_default value from env |
ConnStr_defaultConnStr_default | ConnStr_default Val z ENVConnStr_default val from env |
stripPrefixstripPrefix
stripPrefix
: wartość logiczna, wartość domyślna to false
.stripPrefix
: boolean, defaults to false
.
Poprzedzające znaczniki XML oddzielają ustawienia aplikacji od parametrów połączenia, ale wymagają wszystkich kluczy w pliku web.config , aby użyć określonego prefiksu.The preceding XML markup separates app settings from connection strings but requires all the keys in the web.config file to use the specified prefix. Na przykład AppSetting
należy dodać prefiks do ServiceID
klucza ("AppSetting_ServiceID").For example, the prefix AppSetting
must be added to the ServiceID
key ("AppSetting_ServiceID"). W przypadku stripPrefix
, prefiks nie jest używany w pliku web.config .With stripPrefix
, the prefix is not used in the web.config file. Prefiks jest wymagany w źródle Configuration Builder (na przykład w środowisku). Oczekujemy, że większość deweloperów będzie korzystać z programu stripPrefix
.The prefix is required in the configuration builder source (for example, in the environment.) We anticipate most developers will use stripPrefix
.
Aplikacje zwykle przełączają się na prefiks.Applications typically strip off the prefix. Poniższy web.config przykładek prefiksu:The following web.config strips the prefix:
<configuration>
<configSections>
<section name="configBuilders"
type="System.Configuration.ConfigurationBuildersSection,
System.Configuration, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="AS_Environment" mode="Greedy" prefix="AppSetting_"
stripPrefix="true"
type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Environment,
Version=1.0.0.0, Culture=neutral" />
<add name="CS_Environment" mode="Greedy" prefix="ConnStr_"
stripPrefix="true"
type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Environment,
Version=1.0.0.0, Culture=neutral" />
</builders>
</configBuilders>
<appSettings configBuilders="AS_Environment">
<add key="ServiceID" value="ServiceID value from web.config" />
<add key="default" value="AppSetting_default value from web.config" />
</appSettings>
<connectionStrings configBuilders="CS_Environment">
<add name="default" connectionString="Data Source=web.config/mydb.db" />
</connectionStrings>
W poprzednim pliku web.config default
klucz znajduje się zarówno w, <appSettings/>
jak i <connectionStrings/>
.In the preceding web.config file, the default
key is in both the <appSettings/>
and <connectionStrings/>
.
Na poniższej ilustracji przedstawiono <appSettings/>
i <connectionStrings/>
klucze/wartości z poprzedniego web.config zestawu plików w edytorze środowiska:The following image shows the <appSettings/>
and <connectionStrings/>
keys/values from the preceding web.config file set in the environment editor:
Poniższy kod odczytuje <appSettings/>
<connectionStrings/>
klucze i/wartości zawarte w poprzednim pliku web.config :The following code reads the <appSettings/>
and <connectionStrings/>
keys/values contained in the preceding web.config file:
public partial class About2 : Page
{
public string ServiceID { get; set; }
public string AppSetting_default { get; set; }
public string ConString { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
ServiceID = ConfigurationManager.AppSettings["ServiceID"];
AppSetting_default = ConfigurationManager.AppSettings["default"];
ConString = ConfigurationManager.ConnectionStrings["default"]
?.ConnectionString;
}
}
Poprzedni kod ustawi wartości właściwości na:The preceding code will set the property values to:
- Wartości w pliku web.config , jeśli klucze nie są ustawione w zmiennych środowiskowych.The values in the web.config file if the keys are not set in environment variables.
- Wartości zmiennej środowiskowej, jeśli jest ustawiona.The values of the environment variable, if set.
Na przykład przy użyciu poprzedniego pliku web.config , klucze/wartości w poprzednim obrazie edytora środowiska i Poprzedni kod są ustawione następujące wartości:For example, using the previous web.config file, the keys/values in the previous environment editor image, and the previous code, the following values are set:
KluczKey | WartośćValue |
---|---|
ServiceIDServiceID | AppSetting_ServiceID ze zmiennych ENVAppSetting_ServiceID from env variables |
defaultdefault | AppSetting_default wartość z ENVAppSetting_default value from env |
defaultdefault | ConnStr_default Val z ENVConnStr_default val from env |
tokenPatterntokenPattern
tokenPattern
: Ciąg, wartość domyślna to @"\$\{(\w+)\}"
tokenPattern
: String, defaults to @"\$\{(\w+)\}"
Expand
Zachowanie konstruktorów przeszukuje nieprzetworzony kod XML pod kątem tokenów, które wyglądają następująco ${token}
.The Expand
behavior of the builders searches the raw XML for tokens that look like ${token}
. Wyszukiwanie jest wykonywane z domyślnym wyrażeniem regularnym @"\$\{(\w+)\}"
.Searching is done with the default regular expression @"\$\{(\w+)\}"
. Zestaw znaków, który jest zgodny, \w
jest bardziej rygorystyczny niż XML i wiele źródeł konfiguracji Zezwalaj.The set of characters that matches \w
is more strict than XML and many configuration sources allow. Użyj tokenPattern
@"\$\{(\w+)\}"
, gdy w nazwie tokenu są wymagane więcej znaków niż.Use tokenPattern
when more characters than @"\$\{(\w+)\}"
are required in the token name.
tokenPattern
ParametrytokenPattern
: String:
- Umożliwia deweloperom zmianę wyrażenia regularnego używanego do dopasowywania tokenu.Allows developers to change the regex that is used for token matching.
- Sprawdzanie poprawności nie jest wykonywane, aby upewnić się, że jest to dobrze sformułowane wyrażenie regularne.No validation is done to make sure it is a well-formed, non-dangerous regex.
- Musi zawierać grupę przechwytywania.It must contain a capture group. Całe wyrażenie regularne musi być zgodne z całym tokenem.The entire regex must match the entire token. Pierwsze przechwytywanie musi być nazwą tokenu, aby wyszukać w źródle konfiguracji.The first capture must be the token name to look up in the configuration source.
Konstruktory konfiguracji w Microsoft.Configuration.ConfigurationBuildersConfiguration builders in Microsoft.Configuration.ConfigurationBuilders
EnvironmentConfigBuilderEnvironmentConfigBuilder
<add name="Environment"
[mode|prefix|stripPrefix|tokenPattern]
type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Environment" />
EnvironmentConfigBuilder:The EnvironmentConfigBuilder:
- Jest najprostszym z konstruktorów konfiguracji.Is the simplest of the configuration builders.
- Odczytuje wartości ze środowiska.Reads values from the environment.
- Nie ma żadnych dodatkowych opcji konfiguracji.Does not have any additional configuration options.
name
Wartość atrybutu jest dowolny.Thename
attribute value is arbitrary.
Uwaga: W środowisku kontenera systemu Windows zmienne ustawione w czasie wykonywania są wstrzykiwane tylko do środowiska procesu EntryPoint.Note: In a Windows container environment, variables set at run time are only injected into the EntryPoint process environment. Aplikacje uruchamiane jako usługa lub proces poza elementem EntryPoint nie pobierają tych zmiennych, chyba że są one wprowadzane przez mechanizm w kontenerze.Apps that run as a service or a non-EntryPoint process do not pick up these variables unless they are otherwise injected through a mechanism in the container. W przypadku / kontenerów opartych naASP.NETIIS bieżąca wersja ServiceMonitor.exe obsługuje tę opcję tylko w ramach tej usługi.For IIS/ASP.NET-based containers, the current version of ServiceMonitor.exe handles this in the DefaultAppPool only. Inne warianty kontenerów opartych na systemie Windows mogą wymagać opracowania własnego mechanizmu wstrzykiwania dla procesów poza punktami wejścia.Other Windows-based container variants may need to develop their own injection mechanism for non-EntryPoint processes.
UserSecretsConfigBuilderUserSecretsConfigBuilder
Warning
Nigdy nie przechowuj haseł, poufnych parametrów połączenia lub innych poufnych danych w kodzie źródłowym.Never store passwords, sensitive connection strings, or other sensitive data in source code. Wpisy tajne produkcji nie powinny być używane do celów deweloperskich i testowych.Production secrets should not be used for development or test.
<add name="UserSecrets"
[mode|prefix|stripPrefix|tokenPattern]
(userSecretsId="{secret string, typically a GUID}" | userSecretsFile="~\secrets.file")
[optional="true"]
type="Microsoft.Configuration.ConfigurationBuilders.UserSecretsConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.UserSecrets" />
Ten konstruktor konfiguracji udostępnia funkcję podobną do ASP.NET Core Secret Manager.This configuration builder provides a feature similar to ASP.NET Core Secret Manager.
UserSecretsConfigBuilder można używać w projektach .NET Framework, ale musi być określony plik tajny.The UserSecretsConfigBuilder can be used in .NET Framework projects, but a secrets file must be specified. Alternatywnie można zdefiniować UserSecretsId
Właściwość w pliku projektu i utworzyć Nieprzetworzony plik tajny we właściwym miejscu do odczytu.Alternatively, you can define the UserSecretsId
property in the project file and create the raw secrets file in the correct location for reading. Aby zachować zależności zewnętrzne poza projektem, plik tajny jest sformatowany w formacie XML.To keep external dependencies out of your project, the secret file is XML formatted. Formatowanie XML jest szczegółami implementacji i nie powinno się opierać na tym formacie.The XML formatting is an implementation detail, and the format should not be relied upon. Jeśli musisz udostępnić secrets.jsw pliku z projektami .NET Core, rozważ użycie SimpleJsonConfigBuilder.If you need to share a secrets.json file with .NET Core projects, consider using the SimpleJsonConfigBuilder. SimpleJsonConfigBuilder
Format platformy .NET Core powinien również być traktowany jak szczegóły implementacji, aby zmienić.The SimpleJsonConfigBuilder
format for .NET Core should also be considered an implementation detail subject to change.
Atrybuty konfiguracji dla UserSecretsConfigBuilder
:Configuration attributes for UserSecretsConfigBuilder
:
userSecretsId
— Jest to preferowana metoda identyfikacji pliku tajnego XML.userSecretsId
- This is the preferred method for identifying an XML secrets file. Działa podobnie do programu .NET Core, który używaUserSecretsId
właściwości projektu do przechowywania tego identyfikatora.It works similar to .NET Core, which uses aUserSecretsId
project property to store this identifier. Ciąg musi być unikatowy, nie musi być identyfikatorem GUID.The string must be unique, it doesn't need to be a GUID. Przy użyciu tego atrybutu należyUserSecretsConfigBuilder
szukać w dobrze znanej lokalizacji lokalnej (%APPDATA%\Microsoft\UserSecrets\<UserSecrets Id>\secrets.xml
) dla pliku tajnego należącego do tego identyfikatora.With this attribute, theUserSecretsConfigBuilder
look in a well-known local location (%APPDATA%\Microsoft\UserSecrets\<UserSecrets Id>\secrets.xml
) for a secrets file belonging to this identifier.userSecretsFile
-Opcjonalny atrybut określający plik zawierający wpisy tajne.userSecretsFile
- An optional attribute specifying the file containing the secrets. Ten~
znak może być używany na początku do odwoływania się do katalogu głównego aplikacji.The~
character can be used at the start to reference the application root. Ten atrybut lubuserSecretsId
atrybut jest wymagany.Either this attribute or theuserSecretsId
attribute is required. Jeśli oba są określone,userSecretsFile
ma pierwszeństwo.If both are specified,userSecretsFile
takes precedence.optional
: Boolean, wartość domyślnatrue
— uniemożliwia wyjątek, jeśli nie można znaleźć pliku tajnego.optional
: boolean, default valuetrue
- Prevents an exception if the secrets file cannot be found.name
Wartość atrybutu jest dowolny.Thename
attribute value is arbitrary.
Plik tajny ma następujący format:The secrets file has the following format:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<secrets ver="1.0">
<secret name="secret key name" value="secret value" />
</secrets>
</root>
AzureKeyVaultConfigBuilderAzureKeyVaultConfigBuilder
<add name="AzureKeyVault"
[mode|prefix|stripPrefix|tokenPattern]
(vaultName="MyVaultName" |
uri="https:/MyVaultName.vault.azure.net")
[version="secrets version"]
[preloadSecretNames="true"]
type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Azure" />
AzureKeyVaultConfigBuilder odczytuje wartości przechowywane w Azure Key Vault.The AzureKeyVaultConfigBuilder reads values stored in the Azure Key Vault.
vaultName
jest wymagana (nazwa magazynu lub identyfikator URI magazynu).vaultName
is required (either the name of the vault or a URI to the vault). Inne atrybuty umożliwiają kontrolę nad tym, z którym magazynem ma zostać nawiązane połączenie, ale tylko wtedy, gdy aplikacja nie działa w środowisku, w którym działa program Microsoft.Azure.Services.AppAuthentication
.The other attributes allow control about which vault to connect to, but are only necessary if the application is not running in an environment that works with Microsoft.Azure.Services.AppAuthentication
. Biblioteka uwierzytelniania usług platformy Azure służy do automatycznego pobierania informacji o połączeniu ze środowiska wykonywania, jeśli jest to możliwe.The Azure Services Authentication library is used to automatically pick up connection information from the execution environment if possible. Można przesłonić automatyczne pobranie informacji o połączeniu, podając parametry połączenia.You can override automatically pick up of connection information by providing a connection string.
vaultName
-Wymagane, jeśliuri
nie jest podany.vaultName
- Required ifuri
in not provided. Określa nazwę magazynu w ramach subskrypcji platformy Azure, z którego ma zostać odczytana para klucz/wartość.Specifies the name of the vault in your Azure subscription from which to read key/value pairs.uri
— Nawiązuje połączenie z innymi dostawcami Key Vault o określonejuri
wartości.uri
- Connects to other Key Vault providers with the specifieduri
value. Jeśli nie zostanie określony, platforma Azure (vaultName
) jest dostawcą magazynu.If not specified, Azure (vaultName
) is the vault provider.version
-Azure Key Vault udostępnia funkcję przechowywania wersji dla wpisów tajnych.version
- Azure Key Vault provides a versioning feature for secrets. Jeśliversion
jest określony, Konstruktor pobiera tylko wpisy tajne pasujące do tej wersji.Ifversion
is specified, the builder only retrieves secrets matching this version.preloadSecretNames
-Domyślnie ten Konstruktor bada wszystkie nazwy kluczy w magazynie kluczy po jego zainicjowaniu.preloadSecretNames
- By default, this builder querys all key names in the key vault when it is initialized. Aby uniemożliwić odczytywanie wszystkich wartości klucza, ustaw ten atrybut nafalse
.To prevent reading all key values, set this attribute tofalse
. Ustawienie tej opcji umożliwiafalse
odczytywanie wpisów tajnych pojedynczo.Setting this tofalse
reads secrets one at a time. Odczytywanie wpisów tajnych po jednej naraz może być przydatne, jeśli magazyn zezwala na dostęp "Get", ale nie do "list".Reading secrets one at a time can useful if the vault allows "Get" access but not "List" access. Uwaga: W przypadku korzystania zGreedy
trybupreloadSecretNames
musi byćtrue
(wartość domyślna).Note: When usingGreedy
mode,preloadSecretNames
must betrue
(the default.)
KeyPerFileConfigBuilderKeyPerFileConfigBuilder
<add name="KeyPerFile"
[mode|prefix|stripPrefix|tokenPattern]
(directoryPath="PathToSourceDirectory")
[ignorePrefix="ignore."]
[keyDelimiter=":"]
[optional="false"]
type="Microsoft.Configuration.ConfigurationBuilders.KeyPerFileConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.KeyPerFile" />
KeyPerFileConfigBuilder to podstawowy Konstruktor konfiguracji, który używa plików katalogu jako źródła wartości.KeyPerFileConfigBuilder is a basic configuration builder that uses a directory's files as a source of values. Nazwa pliku jest kluczem, a zawartość jest wartością.A file's name is the key, and the contents are the value. Ten konstruktor konfiguracji może być przydatny w przypadku uruchamiania w środowisku organizowania kontenerów.This configuration builder can be useful when running in an orchestrated container environment. Systemy takie jak Docker Swarm i Kubernetes zapewniają secrets
swoje zorganizowane kontenery systemu Windows w tym samym pliku.Systems like Docker Swarm and Kubernetes provide secrets
to their orchestrated windows containers in this key-per-file manner.
Szczegóły atrybutu:Attribute details:
directoryPath
Potrzeb.directoryPath
- Required. Określa ścieżkę do przeszukiwania wartości.Specifies a path to look in for values. Wpisy tajne Docker for Windows są domyślnie przechowywane w katalogu C:\ProgramData\Docker\secrets .Docker for Windows secrets are stored in the C:\ProgramData\Docker\secrets directory by default.ignorePrefix
-Pliki, które zaczynają się od tego prefiksu, są wykluczone.ignorePrefix
- Files that start with this prefix are excluded. Wartość domyślna to "Ignore.".Defaults to "ignore.".keyDelimiter
-Wartość domyślna tonull
.keyDelimiter
- Default value isnull
. Jeśli ta wartość jest określona, Konstruktor konfiguracji przechodzi przez wiele poziomów katalogu, tworząc nazwy kluczy przy użyciu tego ogranicznika.If specified, the configuration builder traverses multiple levels of the directory, building up key names with this delimiter. Jeśli ta wartość jest równanull
, Konstruktor konfiguracji będzie wyglądał tylko na najwyższym poziomie katalogu.If this value isnull
, the configuration builder only looks at the top level of the directory.optional
-Wartość domyślna tofalse
.optional
- Default value isfalse
. Określa, czy Konstruktor konfiguracji powinien spowodować błędy, jeśli katalog źródłowy nie istnieje.Specifies whether the configuration builder should cause errors if the source directory doesn't exist.
SimpleJsonConfigBuilderSimpleJsonConfigBuilder
Warning
Nigdy nie przechowuj haseł, poufnych parametrów połączenia lub innych poufnych danych w kodzie źródłowym.Never store passwords, sensitive connection strings, or other sensitive data in source code. Wpisy tajne produkcji nie powinny być używane do celów deweloperskich i testowych.Production secrets should not be used for development or test.
<add name="SimpleJson"
[mode|prefix|stripPrefix|tokenPattern]
jsonFile="~\config.json"
[optional="true"]
[jsonMode="(Flat|Sectional)"]
type="Microsoft.Configuration.ConfigurationBuilders.SimpleJsonConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Json" />
Projekty .NET Core często używają plików JSON do konfiguracji..NET Core projects frequently use JSON files for configuration. Konstruktor SimpleJsonConfigBuilder umożliwia korzystanie z plików języka JSON platformy .NET Core w .NET Framework.The SimpleJsonConfigBuilder builder allows .NET Core JSON files to be used in the .NET Framework. Ten konstruktor konfiguracji zapewnia podstawowe mapowanie ze źródła klucza prostego/wartości do określonych obszarów klucz/wartość konfiguracji .NET Framework.This configuration builder provides a basic mapping from a flat key/value source into specific key/value areas of .NET Framework configuration. Ten program Configuration Builder nie zapewnia konfiguracji hierarchicznych.This configuration builder does not provide for hierarchical configurations. Plik kopii zapasowej JSON jest podobny do słownika, a nie złożonego obiektu hierarchicznego.The JSON backing file is similar to a dictionary, not a complex hierarchical object. Można użyć wielopoziomowego pliku hierarchicznego.A multi-level hierarchical file can be used. Ten dostawca flatten
s głębokości przez dołączenie nazwy właściwości na każdym poziomie przy użyciu :
jako ogranicznika.This provider flatten
s the depth by appending the property name at each level using :
as a delimiter.
Szczegóły atrybutu:Attribute details:
jsonFile
Potrzeb.jsonFile
- Required. Określa plik JSON, z którego ma zostać odczytany.Specifies the JSON file to read from. Ten~
znak może być używany na początku do odwoływania się do katalogu głównego aplikacji.The~
character can be used at the start to reference the app root.optional
-Boolean, wartość domyślna totrue
.optional
- Boolean, default value istrue
. Zapobiega zgłaszaniu wyjątków, jeśli nie można znaleźć pliku JSON.Prevents throwing exceptions if the JSON file cannot be found.jsonMode
-[Flat|Sectional]
.jsonMode
-[Flat|Sectional]
. Wartość domyślna toFlat
.Flat
is the default. GdyjsonMode
ma wartośćFlat
, plik JSON jest pojedynczym prostym źródłem klucza/wartości.WhenjsonMode
isFlat
, the JSON file is a single flat key/value source.EnvironmentConfigBuilder
IAzureKeyVaultConfigBuilder
są również pojedynczymi płaskimi źródłami klucz/wartość.TheEnvironmentConfigBuilder
andAzureKeyVaultConfigBuilder
are also single flat key/value sources. GdySimpleJsonConfigBuilder
jest skonfigurowany wSectional
trybie:When theSimpleJsonConfigBuilder
is configured inSectional
mode:- Plik JSON jest koncepcyjnie podzielony na najwyższego poziomu do wielu słowników.The JSON file is conceptually divided just at the top level into multiple dictionaries.
- Każdy słownik jest stosowany tylko do sekcji konfiguracji, która pasuje do dołączonej nazwy właściwości najwyższego poziomu.Each of the dictionaries is only applied to the configuration section that matches the top-level property name attached to them. Na przykład:For example:
{
"appSettings" : {
"setting1" : "value1",
"setting2" : "value2",
"complex" : {
"setting1" : "complex:value1",
"setting2" : "complex:value2",
}
}
}
Kolejność kompilacji konfiguracjiConfiguration builders order
Zobacz kolejność wykonywania ConfigurationBuilders w repozytorium GitHub /MicrosoftConfigurationBuilders .See ConfigurationBuilders Order of Execution in the aspnet/MicrosoftConfigurationBuilders GitHub repository.
Implementowanie niestandardowego konstruktora konfiguracji klucza/wartościImplementing a custom key/value configuration builder
Jeśli konstruktorzy konfiguracji nie spełnią Twoich potrzeb, można napisać ją niestandardową.If the configuration builders don't meet your needs, you can write a custom one. KeyValueConfigBuilder
Klasa bazowa obsługuje tryby podstawienia i większość kwestii związanych z prefiksami.The KeyValueConfigBuilder
base class handles substitution modes and most prefix concerns. Wdrożenie projektu wymaga tylko:An implementing project need only:
- Dziedzicz z klasy podstawowej i zaimplementuj podstawowe źródło par klucz/wartość za pomocą
GetValue
iGetAllValues
:Inherit from the base class and implement a basic source of key/value pairs through theGetValue
andGetAllValues
: - Dodaj Microsoft.Configuration.ConfigurationBuilders. Base do projektu.Add the Microsoft.Configuration.ConfigurationBuilders.Base to the project.
using Microsoft.Configuration.ConfigurationBuilders;
using System.Collections.Generic;
public class MyCustomConfigBuilder : KeyValueConfigBuilder
{
public override string GetValue(string key)
{
// Key lookup should be case-insensitive, because most key/value collections in
// .NET Framework config sections are case-insensitive.
return "Value for given key, or null.";
}
public override ICollection<KeyValuePair<string, string>> GetAllValues(string prefix)
{
// Populate the return collection.
return new Dictionary<string, string>() { { "one", "1" }, { "two", "2" } };
}
}
KeyValueConfigBuilder
Klasa bazowa zapewnia większość pracy i spójne zachowanie między konstruktorami konfiguracji klucz/wartość.The KeyValueConfigBuilder
base class provides much of the work and consistent behavior across key/value configuration builders.