- .NET Core run-time configuration settings
- runtimeconfig.json
- Example [appname].runtimeconfig.json file
- Example runtimeconfig.template.json file
- MSBuild properties
- Environment variables
- Настройка приложений с использованием файлов конфигурации Configuring Apps by using Configuration Files
- Формат файлов конфигурации Configuration File Format
- Файлы конфигурации компьютеров Machine Configuration Files
- Файлы конфигурации приложений Application Configuration Files
- Файлы конфигурации безопасности Security Configuration Files
- в этом разделе In This Section
.NET Core run-time configuration settings
.NET Core supports the use of configuration files and environment variables to configure the behavior of .NET Core applications at run time. Run-time configuration is an attractive option if:
You don’t own or control the source code for an application and therefore are unable to configure it programmatically.
Multiple instances of your application run at the same time on a single system, and you want to configure each for optimum performance.
This documentation is a work in progress. If you notice that the information presented here is either incomplete or inaccurate, either open an issue to let us know about it, or submit a pull request to address the issue. For information about submitting pull requests for the dotnet/docs repository, see the contributor’s guide.
.NET Core provides the following mechanisms for configuring application behavior at run time:
Configuring a run-time option by using an environment variable applies the setting to all .NET Core apps. Configuring a run-time option in the runtimeconfig.json or project file applies the setting to that application only.
Some configuration values can also be set programmatically by calling the AppContext.SetSwitch method.
The articles in this section of the documentation are organized by category, for example, debugging and garbage collection. Where applicable, configuration options are shown for runtimeconfig.json files, MSBuild properties, environment variables, and, for cross-reference, app.config files for .NET Framework projects.
runtimeconfig.json
When a project is built, an [appname].runtimeconfig.json file is generated in the output directory. If a runtimeconfig.template.json file exists in the same folder as the project file, any configuration options it contains are inserted into the [appname].runtimeconfig.json file. If you’re building the app yourself, put any configuration options in the runtimeconfig.template.json file. If you’re just running the app, insert them directly into the [appname].runtimeconfig.json file.
The [appname].runtimeconfig.json file will get overwritten on subsequent builds.
Specify run-time configuration options in the configProperties section of the runtimeconfig.json files. This section has the form:
Example [appname].runtimeconfig.json file
If you’re placing the options in the output JSON file, nest them under the runtimeOptions property.
Example runtimeconfig.template.json file
If you’re placing the options in the template JSON file, omit the runtimeOptions property.
MSBuild properties
Some run-time configuration options can be set using MSBuild properties in the .csproj or .vbproj file of SDK-style .NET Core projects. MSBuild properties take precedence over options set in the runtimeconfig.template.json file.
Here is an example SDK-style project file with MSBuild properties for configuring run-time behavior:
MSBuild properties for configuring run-time behavior are noted in the individual articles for each area, for example, garbage collection. They are also listed in the Run-time configuration section of the MSBuild properties reference for SDK-style projects.
Environment variables
Environment variables can be used to supply some run-time configuration information. Configuring a run-time option by using an environment variable applies the setting to all .NET Core apps. Configuration knobs specified as environment variables generally have the prefix COMPlus_.
You can define environment variables from the Windows Control Panel, at the command line, or programmatically by calling the Environment.SetEnvironmentVariable(String, String) method on both Windows and Unix-based systems.
The following examples show how to set an environment variable at the command line:
Настройка приложений с использованием файлов конфигурации Configuring Apps by using Configuration Files
Среда .NET Framework предоставляет разработчикам и администраторам возможность управления и гибкой настройки способа выполнения приложений с помощью файлов конфигурации. The .NET Framework, through configuration files, gives developers and administrators control and flexibility over the way applications run. Файлы конфигурации имеют формат XML, и при необходимости их можно изменять. Configuration files are XML files that can be changed as needed. Администратор может контролировать, к каким из защищенных ресурсов может осуществлять доступ приложение, какие оно будет использовать версии сборок и где расположены удаленные объекты и приложения. An administrator can control which protected resources an application can access, which versions of assemblies an application will use, and where remote applications and objects are located. Разработчики могут задавать параметры в файлах конфигурации, устраняя необходимость в перекомпиляции приложения при каждом изменении той или иной установки. Developers can put settings in configuration files, eliminating the need to recompile an application every time a setting changes. В этом разделе рассказывается, какие параметры могут быть настроены и для чего может потребоваться настройка приложения. This section describes what can be configured and why configuring an application might be useful.
С помощью классов из пространства имен System.Configuration управляемый код может считывать установки из конфигурационных файлов, но не записывать их в эти файлы. Managed code can use the classes in the System.Configuration namespace to read settings from the configuration files, but not to write settings to those files.
В этом разделе описан синтаксис файлов конфигурации и приведены сведения о трех типах таких файлов: конфигурации компьютера, приложения и безопасности. This topic describes the syntax of configuration files and provides information about the three types of configuration files: machine, application, and security.
Формат файлов конфигурации Configuration File Format
Файлы конфигурации состоят из элементов, которые являются логическими структурами данных, задающими сведения о конфигурации. Configuration files contain elements, which are logical data structures that set configuration information. Начало и конец каждого элемента в файле конфигурации отмечены специальными тегами. Within a configuration file, you use tags to mark the beginning and end of an element. Например, элемент состоит из дочерних элементов . For example, the element consists of child elements . Пустой элемент будет записан как или . An empty element would be written as or .
Как и во всех XML-файлах, в файлах конфигурации учитывается регистр. As with all XML files, the syntax in configuration files is case-sensitive.
Параметры конфигурации задаются с помощью предварительно определенных атрибутов (пар имя-значение) в открывающем теге элемента. You specify configuration settings using predefined attributes, which are name/value pairs inside an element’s start tag. В следующем примере заданы два атрибута ( version и href ) элемента , определяющие для среды выполнения расположение сборок (дополнительные сведения см. в разделе Указание расположения сборки). The following example specifies two attributes ( version and href ) for the element, which specifies where the runtime can locate an assembly (for more information, see Specifying an Assembly’s Location).
Файлы конфигурации компьютеров Machine Configuration Files
В файле конфигурации компьютера, Machine.config, задаются параметры, влияющие на работу компьютера в целом. The machine configuration file, Machine.config, contains settings that apply to an entire computer. Этот файл находится в каталоге %путь установки среды выполнения%\Config. This file is located in the %runtime install path%\Config directory. В файле Machine.config задаются параметры конфигурации для привязки сборок компьютера, встроенных каналов удаленного взаимодействия и ASP.NET. Machine.config contains configuration settings for machine-wide assembly binding, built-in remoting channels, and ASP.NET.
Система конфигурации сначала просматривает файл конфигурации компьютера для элемента и других разделов конфигурации, которые может определить разработчик. The configuration system first looks in the machine configuration file for the element and other configuration sections that a developer might define. Затем поиск выполняется в файле конфигурации приложения. It then looks in the application configuration file. Для облегчения управления файлом конфигурации компьютера рекомендуется переместить эти параметры в файл конфигурации приложения. To keep the machine configuration file manageable, it is best to put these settings in the application configuration file. Однако размещение параметров в файле конфигурации компьютера упрощает управление системой. However, putting the settings in the machine configuration file can make your system more maintainable. Например, при наличии компонентов сторонних производителей, используемых сервером и клиентами, рекомендуется разместить параметры этих компонентов в одном файле. For example, if you have a third-party component that both your client and server application uses, it is easier to put the settings for that component in one place. В этом случае следует задавать параметры в файле конфигурации компьютера, чтобы не дублировать параметры в разных файлах. In this case, the machine configuration file is the appropriate place for the settings, so you don’t have the same settings in two different files.
При развертывании приложения с помощью команды XCOPY файл конфигурации компьютера не копируется. Deploying an application using XCOPY will not copy the settings in the machine configuration file.
Дополнительные сведения об использовании файла конфигурации компьютера средой CLR для привязки сборок см. в разделе Обнаружение сборок в среде выполнения. For more information about how the common language runtime uses the machine configuration file for assembly binding, see How the Runtime Locates Assemblies.
Файлы конфигурации приложений Application Configuration Files
В файле конфигурации приложения находятся параметры приложения. An application configuration file contains settings that are specific to an app. В этом файле содержатся параметры конфигурации, считываемые средой CLR (например, политика привязки сборок, удаленные объекты и т. д.) и приложением. This file includes configuration settings that the common language runtime reads (such as assembly binding policy, remoting objects, and so on), and settings that the app can read.
Имя и расположение файла конфигурации приложения зависят от места размещения приложения, которым может быть одно из указанных ниже. The name and location of the application configuration file depend on the app’s host, which can be one of the following:
Приложение, размещенное в исполняемом файле. Executable–hosted app.
Такие приложения имеют два файла конфигурации: исходный файл конфигурации, который изменяется разработчиком во время разработки, и выходной файл, распространяемый с приложением. These apps have two configuration files: a source configuration file, which is modified by the developer during development, and an output file that is distributed with the app.
При разработке в Visual Studio разместите исходный файл конфигурации приложения в каталоге проекта и установите для его свойства Копировать в выходной каталог значение Всегда копировать или Копировать, если новее. When you develop in Visual Studio, place the source configuration file for your app in the project directory and set its Copy To Output Directory property to Copy always or Copy if newer. Имя файла конфигурации — это имя приложения с расширением CONFIG. The name of the configuration file is the name of the app with a .config extension. Например, исходный файл конфигурации приложения myApp.exe должен называться myApp.exe.config. For example, an app called myApp.exe should have a source configuration file called myApp.exe.config.
Visual Studio автоматически копирует исходный файл конфигурации в каталог, где находится скомпилированная сборка, чтобы создать выходной файл конфигурации, развертываемый вместе с приложением. Visual Studio automatically copies the source configuration file to the directory where the compiled assembly is placed to create the output configuration file, which is deployed with the app. В некоторых случаях Visual Studio может изменить выходной файл конфигурации; дополнительные сведения см. в разделе Перенаправление версий сборки на уровне приложения статьи Перенаправление версий сборки. In some cases, Visual Studio may modify the output configuration file; for more information, see the Redirecting assembly versions at the app level section of the Redirecting Assembly Versions article.
Приложение, размещенное в ASP.NET. ASP.NET-hosted app.
Дополнительные сведения о файлах конфигурации ASP.NET см. в разделе Параметры конфигурации ASP.NET. For more information about ASP.NET configuration files, see ASP.NET Configuration Settings.
Приложение, размещенное в Internet Explorer. Internet Explorer-hosted app.
Если для приложения, размещенного в Internet Explorer, определен файл конфигурации, его расположение задается в теге
В этом теге location — это URL-адрес файла конфигурации. In this tag, location is a URL to the configuration file. Таким образом задается базовая папка приложения. This sets the app base. Файл конфигурации должен находиться на том же веб-сайте, что и приложение. The configuration file must be located on the same website as the app.
Файлы конфигурации безопасности Security Configuration Files
В файлах конфигурации безопасности содержатся сведения об иерархии групп кода и наборах разрешений, связанных с уровнем политики. Security configuration files contain information about the code group hierarchy and permission sets associated with a policy level. Для изменения политики безопасности настоятельно рекомендуется использовать средство политики безопасности доступа кода (Caspol.exe), что гарантирует целостность файлов конфигурации безопасности. We strongly recommend that you use the Code Access Security Policy tool (Caspol.exe) to modify security policy to ensure that policy changes do not corrupt the security configuration files.
Начиная с .NET Framework 4, файлы конфигурации безопасности существуют только в том случае, если изменилась политика безопасности. Starting with the .NET Framework 4, the security configuration files are present only if security policy has been changed.
Ниже приведено расположение файлов конфигурации безопасности. The security configuration files are in the following locations:
Файл конфигурации политики предприятия: %путь-установки-среды-выполнения%\Config\Enterprisesec.config Enterprise policy configuration file: %runtime-install-path%\Config\Enterprisesec.config
Файл конфигурации политики компьютера: %путь-установки-среды-выполнения%\Config\Security.config Machine policy configuration file: %runtime-install-path%\Config\Security.config
Файл конфигурации политики пользователя: %USERPROFILE%\Application data\Microsoft\CLR security config\vxx.xx\Security.config User policy configuration file: %USERPROFILE%\Application data\Microsoft\CLR security config\vxx.xx\Security.config
в этом разделе In This Section
Практическое руководство. Поиск сборок с помощью DEVPATH How to: Locate Assemblies by Using DEVPATH
Описание процесса настройки среды выполнения для использования переменной среды DEVPATH при поиске сборок. Describes how to direct the runtime to use the DEVPATH environment variable when searching for assemblies.
Перенаправление версий сборки Redirecting Assembly Versions
Инструкции по указанию местоположения и версии сборки, которая должна использоваться приложением. Describes how to specify the location of an assembly and which version of an assembly to use.
Указание расположения сборки Specifying an Assembly’s Location
Сведения о том, как указать среде выполнения, где она должна осуществлять поиск сборки. Describes how to specify where the runtime should search for an assembly.
Настройка криптографических классов Configuring Cryptography Classes
Описание процесса сопоставления имени алгоритма криптографическому классу и идентификатора объекта в криптографическому алгоритму. Describes how to map an algorithm name to a cryptography class and an object identifier to a cryptography algorithm.
Практическое руководство. Создание политики издателя How to: Create a Publisher Policy
Сведения о том, куда и каким образом нужно добавить файл политики издателя, чтобы задать перенаправление сборки и параметры базового каталога кода. Describes when and how you should add a publisher policy file to specify assembly redirection and code base settings.
Схема файла конфигурации Configuration File Schema
Описывается иерархия схемы для запуска, среды выполнения, сети и других типов параметров конфигурации. Describes the schema hierarchy for startup, runtime, network, and other types of configuration settings.