Name already in use
AspNetCore.Docs / aspnetcore / host-and-deploy / iis / web-config.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
The web.config is a file that is read by IIS and the ASP.NET Core Module to configure an app hosted with IIS.
web.config file location
In order to set up the ASP.NET Core Module correctly, the web.config file must be present at the content root path (typically the app base path) of the deployed app. This is the same location as the website physical path provided to IIS. The web.config file is required at the root of the app to enable the publishing of multiple apps using Web Deploy.
Sensitive files exist on the app’s physical path, such as
The web.config file must be present in the deployment at all times, correctly named, and able to configure the site for normal start up. Never remove the web.config file from a production deployment.
If a web.config file isn’t present in the project, the file is created with the correct processPath and arguments to configure the ASP.NET Core Module and moved to published output.
If a web.config file is present in the project, the file is transformed with the correct processPath and arguments to configure the ASP.NET Core Module and moved to published output. The transformation doesn’t modify IIS configuration settings in the file.
The web.config file may provide additional IIS configuration settings that control active IIS modules. For information on IIS modules that are capable of processing requests with ASP.NET Core apps, see the IIS modules topic.
Creating, transforming, and publishing the web.config file is handled by an MSBuild target ( _TransformWebConfig ) when the project is published. This target is present in the Web SDK targets ( Microsoft.NET.Sdk.Web ). The SDK is set at the top of the project file:
To prevent the Web SDK from transforming the web.config file, use the <IsTransformWebConfigDisabled> property in the project file:
When disabling the Web SDK from transforming the file, the processPath and arguments should be manually set by the developer. For more information, see xref:host-and-deploy/aspnet-core-module.
Configuration of ASP.NET Core Module with web.config
The ASP.NET Core Module is configured with the aspNetCore section of the system.webServer node in the site’s web.config file.
The following web.config file is published for a framework-dependent deployment and configures the ASP.NET Core Module to handle site requests:
The following web.config is published for a self-contained deployment:
The xref:System.Configuration.SectionInformation.InheritInChildApplications%2A property is set to false to indicate that the settings specified within the <location> element aren’t inherited by apps that reside in a subdirectory of the app.
When an app is deployed to Azure App Service, the stdoutLogFile path is set to \\?\%home%\LogFiles\stdout . The path saves stdout logs to the LogFiles folder, which is a location automatically created by the service.
For information on IIS sub-application configuration, see xref:host-and-deploy/iis/advanced#sub-applications.
Attributes of the aspNetCore element
Optional string attribute.
Arguments to the executable specified in processPath .
Optional Boolean attribute.
If true, the 502.5 — Process Failure page is suppressed, and the 502 status code page configured in the web.config takes precedence.
Optional Boolean attribute.
If true, the token is forwarded to the child process listening on %ASPNETCORE_PORT% as a header ‘MS-ASPNETCORE-WINAUTHTOKEN’ per request. It’s the responsibility of that process to call CloseHandle on this token per request.
Optional string attribute.
Specifies the hosting model as in-process ( InProcess / inprocess ) or out-of-process ( OutOfProcess / outofprocess ).
Optional integer attribute.
Specifies the number of instances of the process specified in the processPath setting that can be spun up per app.
†For in-process hosting, the value is limited to 1 .
Setting processesPerApplication is discouraged. This attribute will be removed in a future release.
Required string attribute.
Path to the executable that launches a process listening for HTTP requests. Relative paths are supported. If the path begins with . , the path is considered to be relative to the site root.
Optional integer attribute.
Specifies the number of times the process specified in processPath is allowed to crash per minute. If this limit is exceeded, the module stops launching the process for the remainder of the minute.
Not supported with in-process hosting.
Optional timespan attribute.
Specifies the duration for which the ASP.NET Core Module waits for a response from the process listening on %ASPNETCORE_PORT%.
In versions of the ASP.NET Core Module that shipped with the release of ASP.NET Core 2.1 or later, the requestTimeout is specified in hours, minutes, and seconds.
Doesn’t apply to in-process hosting. For in-process hosting, the module waits for the app to process the request.
Valid values for minutes and seconds segments of the string are in the range 0-59. Use of 60 in the value for minutes or seconds results in a 500 — Internal Server Error.
Optional integer attribute.
Duration in seconds that the module waits for the executable to gracefully shutdown when the app_offline.htm file is detected.
Optional integer attribute.
Duration in seconds that the module waits for the executable to start a process listening on the port. If this time limit is exceeded, the module kills the process.
When hosting in-process: The process is not restarted and does not use the rapidFailsPerMinute setting.
When hosting out-of-process: The module attempts to relaunch the process when it receives a new request and continues to attempt to restart the process on subsequent incoming requests unless the app fails to start rapidFailsPerMinute number of times in the last rolling minute.
A value of 0 (zero) is not considered an infinite timeout.
Optional Boolean attribute.
If true, stdout and stderr for the process specified in processPath are redirected to the file specified in stdoutLogFile .
Optional string attribute.
Specifies the relative or absolute file path for which stdout and stderr from the process specified in processPath are logged. Relative paths are relative to the root of the site. Any path starting with . are relative to the site root and all other paths are treated as absolute paths. Any folders provided in the path are created by the module when the log file is created. Using underscore delimiters, a timestamp, process ID, and file extension ( .log ) are added to the last segment of the stdoutLogFile path. If .\logs\stdout is supplied as a value, an example stdout log is saved as stdout_20180205194132_1934.log in the logs folder when saved on February 5, 2018 at 19:41:32 with a process ID of 1934.
Set environment variables
Environment variables can be specified for the process in the processPath attribute. Specify an environment variable with the <environmentVariable> child element of an <environmentVariables> collection element. Environment variables set in this section take precedence over system environment variables.
The following example sets two environment variables in web.config . ASPNETCORE_ENVIRONMENT configures the app’s environment to Development . A developer may temporarily set this value in the web.config file in order to force the Developer Exception Page to load when debugging an app exception. CONFIG_DIR is an example of a user-defined environment variable, where the developer has written code that reads the value on startup to form a path for loading the app’s configuration file.
[!NOTE] An alternative to setting the environment directly in web.config is to include the <EnvironmentName> property in the publish profile ( .pubxml ) or project file. This approach sets the environment in web.config when the project is published:
[!WARNING] Only set the ASPNETCORE_ENVIRONMENT environment variable to Development on staging and testing servers that aren’t accessible to untrusted networks, such as the Internet.
IIS Config Locations
When modifying IIS sometimes i forget where the config files are located. Let’s write them down so I don’t have to hunt for them in the future.
Server Level Config
The root of the IIS server has it’s own config file. This is the root of all settings under IIS. If you add websites or FTP sites to your server, they all will inherit from these settings.
On Windows 10 (and Windows Server 2016 and higher) these settings are found here:
From a security perspective, it is not a good practice to broadcast too much information about your server. One such example that IIS includes with each response is a header called X-Powered-By . This file is where this is defined:
You can simply remove it from this file, save the changes, and it won’t be broadcast any further.
Starting with IIS 10, you can remove the Server header as well. In the applicationHost.config file, find the following section:
Add an attribute to the element called removeServerHeader , and save the changes:
IIS Express
Running IIS Express from the Command Line
When running IIS Express from the command line, the same configuration for IIS Express can be found here:
Оптимизация ASP.NET — практические советы по работе с IIS
В данной публикации речь пойдёт о настройке важных параметров пула ASP.NET-приложений при вызове удалённых веб-сервисов и активной работе с сетью на стороне сервера через стандартные классы .NET.
Введение
Приходилось ли вам когда-нибудь самим настраивать производственные веб-сервера (production servers) под управлением ОС Windows Server 2008 R2/IIS 7.5 и выше? Для системных администраторов, имеющих большой опыт работы с IIS, скорее всего, это тривиальная задача, но вот для веб-разработчиков, которым по различным причинам порой приходится самим участвовать в настройке «боевых» серверов, данная информация может оказаться весьма полезной.
Предыстория
В конце прошлого года в одной крупной организации мы столкнулись с проблемами производительности веб-серверов при резко увеличившейся пользовательской нагрузке. В веб-приложении на тот момент было зарегистрировано более 200 000 клиентов. В обычном режиме одновременно работает около 1000 пользователей, за день примерно 10-15% уникальных посетителей от общего числа зарегистрированных, поэтому нагрузка относительно невысокая. Однако существуют пиковые нагрузки, при которых система оказывается практически неработоспособной.
Веб-администаторы проверили всё, что можно, и никак не могли понять, в чём дело. Ведь несмотря на то, что по всем основным параметрам системы на физическом уровне с производительностью было всё хорошо, возникали сбои с доступностью сервисов, а в пуле собиралась огромная очередь запросов. В организации используется NLB-кластер на 4 узла (Windows Server 2008 R2 + IIS 7.5 + .NET 4.5), есть запас по загрузке ЦП и памяти, сетевые каналы большие, количество используемых портов достаточное. Все проверки указывали на то, что проблемы кроются в недрах IIS и настройке пула ASP.NET. Живой пример, когда администраторам не помешала бы помощь опытных веб-разработчиков…
1. Параметры конфигурации IIS
Начиная с IIS 7, все настройки конфигурации ASP.NET хранятся в XML-файлах (*.config). Они заменили метабазу, которая использовалась в IIS 6.0 и более ранних версиях.
Схема конфигурационных файлов для IIS 7.x и выше выглядит так:
Рис. 1. Схема конфигурационных файлов
На вершине иерархической конфигурации .NET находится файл machine.config. Он определяет глобальные параметры для конкретной машины. В этом файле определяются поддерживаемые разделы конфигурационных файлов, настраивается рабочий процесс ASP.NET и регистрируются поставщики различных модулей. Для оптимизации процесса инициализации файл machine.config был значительно упрощен, и он располагается в каталоге:
Здесь же находится файл machine.config.comments, который позволяет узнать, какие параметры используются по умолчанию. С помощью этих данных в machine.config можно добавить параметры с переопределенными значениями.
Корнем иерархии конфигурации ASP.NET является файл web.config, расположенный в том же каталоге, что и machine.config. Этот файл включает в себя параметры, которые используются для всех приложений ASP.NET.
- для 32-битной — %WINDIR%\System32\inetsrv\config\
- для 64-битной — %WINDIR%\SysWOW64\inetsrv\config\
Прежде чем начинать настройку конфигурации IIS, обратите внимание на счетчики производительности ASP.NET, оцените текущую и пиковую загрузки системы, зафиксируйте имеющиеся показатели. Проверьте логи на наличие ошибки “HTTP Error 503.2 — Service Unavailable”. Постарайтесь определить, не блокируется ли часть запросов в очереди.
Если производительность системы удовлетворяет потребностям заказчика, то лучше оставить параметры по умолчанию, ведь они рассчитаны для большинства ASP.NET приложений.
При конфигурации IIS можно выделить два основных параметра, влияющих на доступность приложения и его производительность.
1. Параметр appConcurrentRequestLimit — максимальное количество одновременных запросов в приложении. Увеличение числа одновременных запросов IIS расширит доступные ресурсы веб-сервера для обслуживания запросов. Значение по умолчанию — 5000.
Наиболее быстро изменить параметр appConcurrentRequestLimit можно утилитой appcmd.exe через командную строку. Сделать это можно как глобально для всех сайтов IIS через файл ApplicationHost.config, так и для отдельного сайта (приложения).
Выполняем команду, затем открываем в IIS раздел «Configuration Editor» для корневого каталога и проверяем новое значение установленного параметра appConcurrentRequestLimit. Причём здесь же можно вручную изменить это значение.
Рис. 2. Установка параметра appConcurrentRequestLimit
Для установки данного параметра наиболее часто используется формула:
<usersCount * 1.5>, где usersCount — количество одновременно работающих пользователей.
2. Параметр QueueLength — максимальное количество запросов, которые драйвер Http.sys размещает в очереди пула приложений. Когда очередь заполнена, новые запросы получают ошибку «503.2 — Service Unavailable». Значение по умолчанию — 5000.
- глобально для .NET на уровне сервера через machine.config, секция processModel/requestQueueLimit;
- на уровне IIS через ApplicationHost.config: system.web/httpRuntime -> appRequestQueueLimit;
- задать значение параметра queueLength для конкретного пула.
Выполняем команду, затем открываем в IIS раздел «Application Pools», выбираем в списке пул «DefaultAppPool », заходим в меню «Advanced Settings» и проверяем.
Рис. 3. Установка параметра queueLength
В диспетчере IIS выберите узел сервера в дереве, затем нажмите на иконку «Worker Processes»:
Рис. 4. Меню Worker Processes в диспетчере IIS
В появившемся списке вы можете видеть загрузку всех запущенных в текущий момент пулов.
Рис. 5. Просмотр работающих пулов через Worker Processes
При нажатии “View Current Request” появляется таблица со списком адресов обрабатываемых страниц и другими полезными параметрами. Для обновления списка можно нажимать F5 на экране. Таким образом, вы сможете найти «подвисшие» запросы:
Рис. 6. Список текущих запросов в пуле
Для просмотра показателей производительности, конечно, лучше использовать счётчики Performance Monitor, но они не покажут вам, как Requests Monitor, URL-адреса текущих запросов.
2. Настройка ASP.NET
ASP.NET ограничивает число рабочих потоков и потоков портов завершения вызова, используемых для выполнения запросов. Если веб-приложение на стороне сервера активно использует вызовы внешних веб-сервисов, стандартные классы из пространства имён System.NET для организации запросов по сети, то могут возникнуть конфликты низкой производительности и взаимоблокировок. Вначале часть запросов может просто “подвисать”, время выполнения будет значительно возрастать. В худшем случае, если используется классический режим настройки пула (classic pipeline), это вообще может привести к перезагрузке пула (recycle). Обнаружение взаимоблокировки ASP.NET не выполняется для пула, запущенного в integrated mode (по умолчанию в IIS 7 и выше).
Работа пулов приложений в интегрированном режиме имеет несколько преимуществ по сравнению с работой в классическом режиме. Рекомедуется запускать пулы приложений в integrated mode.
На рисунке ниже наглядно видно, как происходит обработка запросов в ASP.NET и какие параметры имеют наиболее важное значение:
Рис. 7. Процесс обработки запросов в ASP.NET
Для оптимальной работы веб-приложений по умолчанию включен режим автоконфигурации настроек пула. В этом случае, cвойство autoConfig равно «true» для секции <processModel> в файле machine.config, а другие ключевые параметры не заданы вообще.
- maxConnection
- maxWorkerThreads / minWorkerThreads
- maxIoThreads / minIoThreads
- minFreeThreads
- minLocalRequestFreeThreads
Таким образом, на сервере с 4-х ядерным процессором максимальное кол-во одновременных подключений к конечному IP-адресу равно 48=12*4 (по умолчанию).
Самый простой способ обойти данное ограничение — это прямо в коде своего ASP.NET приложения в методе Application_Start в файле global.asax указать следующее:
Более гибко настраивать maxconnection лучше через конфигурационные файлы на уровне домена приложения (web.config) или веб-сервера (applicationHost.config). Секция <system.net> содержит параметры, которые определяют, как .NET Framework подключается к сети.
Важно: Схема для адреса параметра maxconnection должна быть такой:
Увеличение maxconnection позволяет делать больше одновременных вызовов к удаленным сервисам. Этот атрибут не влияет на локальные вызовы веб-служб! Необходимо понимать, что недостаточно только обойти ограничение на количество одновременных подключений к сервису. Так как увеличение числа одновременных вызовов приводит к увеличению использования потоков CLR, которые используются для создания удаленных и обработки обратных вызовов.
ASP.NET через параметр maxWorkerThreads устанавливает ограничения потоков на рабочем процессе w3wp.exe (начиная с IIS 7). В связи с тем, что ASP.NET встроена в IIS, процессы ASP.NET формируют запросы на рабочих потоках. Из-за недостаточного количества потоков в CLR ThreadPool запросы будут становиться в очередь и “подвисать”.
Аттрибуты, заданные в секции <processModel>:
1. Параметр maxWorkerThreads — указывает максимальное количество рабочих потоков для каждого процессора в пуле потоков среды CLR. Значение по умолчанию — 20. Максимальное значение — 100.
2. Параметр maxIoThreads — указывает максимальное количество потоков ввода/вывода для каждого процессора в пуле потоков среды CLR. Значение по умолчанию — 20. Максимальное значение — 100.
3. Параметр minWorkerThreads — указывает минимальное количество рабочих потоков для каждого процессора, которые могут быть предоставлены немедленно для обслуживания удаленного запроса. Значение по умолчанию — 1.
4. Параметр minIoThreads — указывает минимальное количество потоков ввода/вывода для каждого процессора, которые могут быть предоставлены немедленно для обработки обратного вызова. Значение по умолчанию — 1.
Параметры minWorkerThreads/minIoThreads позволяют оперативно справиться с внезапно возросшим количеством одновременных подключений, когда в случае бездействия пул потоков может не иметь достаточно времени, чтобы достичь оптимального уровня потоков.
Аттрибуты, заданные в секции <httpRuntime>:
1. Параметр minFreeThreads — определяет количество потоков, которые могут быть использованы для работы, кроме обработки входящих запросов к рабочему процессу. Этот параметр не дает процессу ASP.NET использовать потоки из пула для обработки нового HTTP-запроса, если общее число потоков в пуле опустится ниже этого предела. Значение по умолчанию — 8.
2. Параметр minLocalRequestFreeThreads — определяет минимальное количество свободных потоков, которые ASP.NET держит доступными для выполнения новых локальных запросов. Значение по умолчанию — 4.
Обратите внимание, параметры maxWorkerThreads, minWorkerThreads, maxIoThreads, minIoThreads неявно умножаются на число процессоров, а параметры minFreeThreads и minLocalRequestFreeThreads — нет.
ASP.NET не будет выполнять более, чем следующее количество одновременных запросов:
(maxWorkerThreads * число ЦП) — minFreeThreads
Обратите внимание: на весь пул приложения, то есть на каждый рабочий процесс w3wp.exe, обслуживающий пул, имеется один пул потоков CLR ThreadPool. Для всех доменов приложений (сайтов), настроенных на один пул, используется общий набор потоков. Следовательно, для требовательных к ресурсам приложений лучше использовать отдельные пулы.
3. Рекомендации по оптимизации базовой конфигурации
Прежде всего, необходимо точно определить количество процессоров на веб-сервере. Как вариант, можно посмотреть TaskManager -> вкладка «Performance». Если процессор поддерживает режим HyperThreadingTechnology (HTT), значит половина ядер логические (Logical processors), а не физические (Cores). Например, при включенном режиме HTT процессор с 4-мя физическими ядрами будет работать как 8 логических ядер:
Рис. 8. Окно загрузки процессоров в TaskManager
Также можно попробовать воспользоваться следующими командами в командной строке:
или
Например, на сервере с 4-мя процессорами и свойством autoConfig ASP.NET будет иметь следующие параметры по умолчанию:
maxConnection – 48; maxWorkerThreads – 80; maxIoThreads – 80, minFreeThreads – 8, minLocalRequestFreeThreads – 4.
Если веб-страница на backend-части делает несколько сетевых вызовов для каждого запроса, то MSDN рекомендует использовать следующие настройки конфигурации:
- maxWorkerThreads = 100 | minWorkerThreads = maxWorkerThreads / 2 = 50
- maxIoThreads = 100
- maxConnection = 12 * N
- minFreeThreads = 88 * N
- minLocalRequestFreeThreads = 76 * N, где N — количество процессоров.
Изменения в секцию <processModel> разрешено вносить только в файле machine.config из-за установленного там же атрибута allowDefinition при добавлении секции processModel.
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\Machine.config:
Чтобы иметь возможность устанавливать значения секции processModel для каждого приложения в отдельности через web.config, необходимо установить свойство allowDefinition .
Важно: после внесения изменений требуется обновить Application pools.
Помните, что увеличивать данные параметры нужно только в случае необходимости при наличии достаточного количества ресурсов ЦП.
Для анализа производительности веб-серверов рекомендую настроить счётчики ASP.NET через Performance Monitor:
- ASP.NET Applications\Requests/Sec
- Web Service\ISAPI Extension Requests/sec
- ASP.NET\Requests Current
- ASP.NET\Requests Queued
- ASP.NET\ Requests Rejected
- ASP.NET Applications\Requests Executing
- ASP.NET Applications\Requests Timed Out
- ASP.NET\ Request Execution Time
Возможно, что после проверки счётчиков вам придётся внести корректировки в конфигурацию вашей системы.
Дополнительно
Для лучшего понимания работы IIS рекомендую ознакомиться, как происходит процесс обработки запроса от браузера пользователя до конечного пула приложения ASP.NET в этой полезной статье «Основы архитектуры IIS, или запросопровод для ASP.NET».
Если вы используете IIS8 — не будет лишним обратить внимание на «Полноценное регулирование нагрузки CPU (CPU Throttling)».
Заключение
Для сайтов, которые не совершают частые сетевые запросы на стороне сервера, стандартных настроек пула должно хватать (processModel/autoConfig=“true”). При этом IIS выставит ограничение в 20 рабочих потоков и 12 удаленных соединений на ядро. При превышении этих значений запросы начнут становиться в очередь и производительность веб-приложения упадёт.
Если ваш сайт работает хорошо и вы можете оценить предполагаемую нагрузку на систему, то не стоит ничего менять. Если же у вас начинаются “зависания” при обработке запросов к различным сервисам — не следует сразу винить во всем железо! Лучше внести изменения в базовую конфигурацию ASP.NET. Имейте в виду, что изменение базовых параметров пула приложений непременно приведёт к увеличению загрузки процессора. Оптимальная балансировка всех параметров системы — ключ к стабильной и производительной работе оборудования. Как говорится, “предупрежден — значит вооружен”.
Приглашаю всех поделиться вашим опытом настройки и оптимизации работы производственных веб-серверов на платформе Windows Server.
Anatomy of an IIS7 configuration path
If you have worked with IIS6 and previous versions of IIS, you are most likely familiar with the IIS metabase paths. You know, the ones that look like LM/W3SVC/1/ROOT . These metabase paths serve as a mechanism to identify a part of the IIS website hierarchy, or a url therein, for the purposes of read/writing their configuration settings. For example, the server uses these paths at runtime to retrieve the settings for a particular site, virtual directory, or url in your website, and you use them to manage those settings for your site/virtual directory/url using tools like adsutil.vbs.
As you know, IIS7 repaces the metabase with a whole new configuration system, based on a distributed hierarchy of XML configuration files also used by the .NET Framework/ASP.NET. This confguration system is fundamentally different from the metabase, and so it should come as no suprise that the way configuration paths work is also different.
The concept of configuration paths is fundamental to managing and operating an IIS server, so I wanted to spend some time explaining it in hope that this can help everyone enjoy their IIS7 server just a little bit more If you have come here wondering exactly what the hell is MACHINE/WEBROOT/APPHOST, you have come to the right place.
If you want to skip the background and go straight to how IIS7 configuration paths work, click here .
IIS6 Metabase paths – a blast from the past
First, lets take a quick detour and look at how metabase paths worked in previous versions of IIS. The metabase was a centralized configuration file that contained a configuration tree, with each node of the tree containing a list of configuraton properties/values appropriate for it. The metabase path uniquely identified a node in that tree, so you had something like this:
LM (root node)
AppPools (application pool node)
DefaultAppPool (default application pool)
W3SVC (website node)
1 (website /> ROOT (website root)
vdir1 (virtual directory path = /vdir1)
The metabase hierarchy contained nodes for both the url hierarchy (the W3SVC node) and non-url objects such as Application Pools, FTP service, etc. A metabase path for a url could then be constructed as LM / W3SVC /< SITEID >/ ROOT /< VIRTUALPATH >, where <SITEID> identifies the site and <VIRTUALPATH> specifies the virtual path of the url. This path can then be used to read the settings associated with it from the metabase using the ABO APIs, ADSI, WMI, and various scripts and tools including adsutil.vbs, iisweb.vbs, iisdir.vbs, aspnet_regiis, etc.
IIS7 Configuration paths
In IIS7, the configuration system stores configuration in a hierarchy of files, starting with 3 root configuration files, and descending into distributed web.config configuration files that can be present in any directory of your website to affect the configuration for the url namespace to which the directory corresponds. This hierarchy contains the following:
Framework<version>CONFIGmachine.config (the .NET framework machine.config file, where most .NET sections are declared)
Framework<version>CONFIGweb.config ( the .NET framework root web.config file, where most ASP.NET sections are declared)
%windir%system32inetsrvapplicationHost.config (the IIS7 global web server configuration file, where all IIS7 configuration sections are declared)
delegated web.config files (the distributed configuration files that can be present in any virtual directory of your site or its subdirectory)
In this system, a configuration path has the following syntax:
MACHINE/WEBROOT/APPHOST /< SiteName >/< VirtualPath >
Where MACHINE, WEBROOT, and APPHOST correspond to the above configuration files, <SiteName> identifies the site, and <VirtualPath> identifies the virtual path. Note that the site is no longer identified by id, as before, and instead the site name is used (in IIS7, site name is the unique identifier of a site, unlike the ServerComment in IIS6 which was not unique).
The concept of configuration path in the new world has a dual meaning – it can identify both a configuration file in the distributed file hierarchy, AND identify the configuration path (or url) to which configuration settings are applied.
These concepts are related but not identical, which can be fairly confusing at first. By default, configuration settings set at a particular file in the hierarchy that has path X are applicable to the configuration path X. This means that configuration set in applicationHost.config, identified by the configuration path MACHINE/WEBROOT/APPHOST, is applicable to the configuration path MACHINE/WEBROOT/APPHOST and below (due to the hierarchical configuration inherita
nce). All of the IIS7 configuration settings are by default set at this path, and apply to all sites on the machine.
Likewise, by default, if configuration is written to "MACHINE/WEBROOT/APPHOST/Default Web Site/", it will be placed in the web.config file in the root of "Default Web Site", and apply to all urls in the site.
However, the configuration system supports the concept of location tags, which allow configuration to be set at the configuration path X, but apply only to a child configuration path. For example, in the applicationHost.config file, it is possible to set configuration like this:
While set at MACHINE/WEBROOT/APPHOST, this configuration is not effective there. Instead, this configuration applies only to "MACHINE/WEBROOT/APPHOST/Default Web Site/vdir1" and will only be visible when read there. It is effectively equivalent to specifying the configuration in a web.config file in the "vdir1" virtual directory of the "Default Web Site".
This example reflects the choice you have as an IIS7 administrator when setting configuration for a particular path:
- Directly at the path itself by placing it in the configuration file that corresponds to the file (creating a delegated, and XCOPY-deployable configuration), or
- Anywhere above it in the hierarchy, using location tags to apply it to a lower path (creating controlled, centralized configuration).
You can use this ability to select a set of configuration that is set in an administrator controlled location (such as the applicationHost.config file), and allow the rest of the configuration to be set by the application owner directly in their application using distributed web.config files. To learn more about configuration locking, see http://www.iis.net/articles/view.aspx/IIS7/Managing-IIS7/Delegation-in-IIS7/Delegating-Permission-in-Config/How-to-Use-Locking-in-IIS7-Configuration.
Finally, a note: the configuration paths in IIS7 DO NOT SPECIFY the actual configuration that you are setting, only the level at which it is set / level at which the configuration applies. This is somewhat unlike IIS6 metabase paths which sometimes carry information about the object being configured, such as the AppPool node. In IIS7, all configuration is stored in section and so you need to specify which section you’d like to edit and set its properties in addition to specifying at which level it should be set.
Using IIS7 configuration paths to manage configuration
Armed with the knowledge about IIS7 configuration paths, lets jump into a few examples of managing your IIS7 server that require the use of these paths. These examples use the AppCmd.exe, although, you will also use the same paths when working with other configuration APIs like Adadmin COM objects, Microsoft.Web.Administration, and WMI.
When working with AppCmd, it is often possible to omit "MACHINE/WEBROOT/APPHOST" when specifying a configuration path, and instead just use the "<SITENAME>/<VIRTUALPATH>" part of it.
1) Finding a site named "Default Web Site"
> %windir%system32inetsrvAppCmd.exe List Site "Default Web Site"
The path to a site is just its name (remember the AppCmd support for omitting the M/W/A part of the path).
2) Finding an application with path /App1 under "Default Web Site"
> %windir%system32inetsrvAppCmd.exe List Site "Default Web Site/App1"
The path to the application is the SITENAME/VirtualPath where VirtualPath is the virtual path of the application.
For more info on the IIS7 site, application, and virtual directory structure and how to manage these objects, see my earlier post about creating IIS7 sites, applications, and virtual directories.
3) Setting configuration for the root of the "Default Web Site"
> %windir%system32inetsrvAppCmd.exe Set Config "Default Web Site/" /section:directoryBrowse /enabled:true
Applied configuration changes to section "system.webServer/directoryBrowse" for "MACHINE/WEBROOT/APPHOST/Default Web Site/" at configuration commit path "MACHINE/WEBROOT/APPHOST/Default Web Site/"
Note that the tool by default wrote the settings to the web.config in the root of the Default Web Site, because that is what the MACHINE/WEBROOT/APPHOST/Default Web Site/ path corresponds to in the file hierarchy. These settings will be effective for that same path (and below).
4) Settings configuration for the root of the "Default Web Site", but setting them at the global (applicationHost.config) level.
> %windir%system32inetsrvAppCmd.exe Set Config "Default Web Site/" /section:directoryBrowse /enabled:true /COMMIT:MACHINE/WEBROOT/APPHOST
Applied configuration changes to section "system.webServer/directoryBrowse" for "MACHINE/WEBROOT/APPHOST/Default Web Site/" at configuration commit path "MACHINE/WEBROOT/APPHOST"
Note the usage of the commit parameter to force the configuration path to be MACHINE/WEBROOT/APPHOST, which results in the configuration being written to applicationHost.config with a location tag to apply them to the MACHINE/WEBROOT/APPHOST/Default Web Site/ configuration path. If you were to open applicationHost.config, you will find the following:
If you were to now read the effective configuration for the server at the global level by using the command below, you will notice that directory browsing is turned OFF there (unless you changed that), meaning that it is turned off by default for all websites.
> %windir%system32inetsrvAppCmd.exe List Config MACHINE/WEBROOT/APPHOST /
section:directoryBrowse
However, if you then see what the settings are for the “Default Web Site/”, you’ll see that directory browsing is turned ON there. This would be the case if you set that configuration directly at the root web.config for the website using step #3, or set it in applicationHost.config with a location tag in step #4.
I hope this example helps you understand the IIS7 configuration paths and how to use them to manage your server. Please comment and let me know if there is anything else that you think needs to be explained here.