Beruflich Dokumente
Kultur Dokumente
This allows for setting general settings at the site level and overriding them when necessary. Any settings in the base Web.config that aren't overridden in the subfolder stay in effect, so the "child" Web.config can be pretty small. You can continue to nest them, so sub-sub-subfolders can get their own Web.config if needed. Some of the most common uses of subfolders are to restrict permission (e.g. requiring authentication or restricting access to resources), but you can also use them to do things like include default namespaces in Views, toggle handlers, etc.
File name
File description
Server
Machine.config
The Machine.config file contains the ASP.NET schema for all of the Web applications on the server. This file is at the top of the configuration merge hierarchy.
IIS
ApplicationHost.config is the root file of the IIS 7.0 configuration system. It includes definitions of all sites, ApplicationHost.config applications, virtual directories, and application pools, as well as global defaults for the Web server settings. It is in the following location:
%windir%\system32\inetsrv\config The Web.config file for the server is stored in the same directory as the Machine.config file and contains default values for most of the system.web configuration sections. At run time, this file is merged second from the top in the configuration hierarchy. The Web.config file for a specific Web site contains settings that apply to the Web site and inherit downward through all of the ASP.NET applications and subdirectories of the site. The Web.config file for a specific ASP.NET application is located in the root directory of the application and contains settings that apply to the Web application and inherit downward through all of the subdirectories in its branch. The Web.config file for an application subdirectory contains settings that apply to this subdirectory and inherit downward through all of the subdirectories in its branch.
Root Web
Web.config
Web site
Web.config
Web.config
Web.config
So your website's configuration's actually inherited a bunch of settings that were set at the server level. That's nice for a few reasons: 1. It allows the ASP.NET / IIS teams to migrate settings that aren't commonly modified from the project template Web.config files to server defaults, keeping your Web.config files smaller and more readable. For example, ASP.NET 4 migrated a bunch of handler registrations to Machine.config, so the Empty ASP.NET Application Web.config is slimmed down to about 8 lines. 2. You can override things at the server level as needed, and they'll take effect for all applications. For example, you can set <deployment retail="true"> on production servers to disable trace output and debug capabilities. 3. You can find a lot of useful information in the Machine.config default settings since they're stored in plain text. For example, the ASP.NET Membership Provider has some defaults set for password requirements and the membership database, and you can look them up by looking in the appropriate .NET framework version's Machine.config. For a default installation of ASP.NET 4, that's found in C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config with a quick search for <membership>.
that both the ApplicationHost.config and Machine.config feed into the configuration settings in your site's Web.config, as shown in Carlos' diagram:
In addition to the understanding how things work part of it, this is also good to know because - based on the info in Tip 2 - you can see what the base settings are, and how you can override them in your application's Web.config. This is why you can do pretty advanced things like configure rules on for the URL Rewrite Module in your application's web.config. Of course, server administrators don't necessarily want to allow any application on the server to modify settings via Web.config, so there are configurable policies in the ApplicationHost.config which state whether individual applications can override settings. There's also an Administration.config file which controls things like Module registration. There's one kind of new update to this list - using aspnet.config for Application Pool tuning. It's found in the same directory as Machine.config, and it's been around since .NET 2.0. However, as of ASP.NET 4 it's been expanded to handle things like concurrency and threading, as explained in Scott Forsyth's post, Setting an aspnet.config File per Application Pool. While not something most ASP.NET developers will need to use, it's good to know that you can control things like maxConcurrentRequestsPerCPU, maxConcurrentThreadsPerCPU and requestQueueLimit at the application pool level.
1 2 3 4 5 6 7
populate a collection. Scott Guthrie blogged about an example in which just adding a new Membership Provider causes problems, because you end up with two providers - the default, and the one you just added. It's important to clear the collection before adding your new provider using the <clear/> element, like this: ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<membership> <providers> <clear/> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="MyDatabase" enablePasswordRetrieval="false" (additional elements removed for brevity) /> </providers> </membership>
As Scott explains, failure to <clear/> the collection first results in both providers attempting to handle membership, which probably isn't what you intended.
Answer 1
8 Votes
In addition to using <clear/> or overwriting the settings in the child web.config, you can use the inheritInChildApplications setting in conjunction with in the parent web.config. Example:
<location path="." inheritInChildApplications="false"> <system.web> <!-- ... --> </system.web> </location>
You can wrap the location around the entire <system.web> or just around specific sections. Some links for more info: inheritInChildApplications on MSDN (read the community content at the bottom for more) StackOverflow: Avoid web.config inheritance in child web application using inheritInChildApplications Blog post: Stopping web.config inheritance
+ More Answers
Since Web.config is so heavily built on the concept of inheritance, it's not surprising that turning it off for a section can have some side effects. The aptly self-named "Run Things Proper Harry," a.k.a. rtpHarry, has written up two good posts covering usage and important things to be aware of.
SOLVED: Breaking parent web.config dependencies in sub applications SOLVED: IIS7, validateIntegratedModeConfiguration and inheritInChildApplications clash
1 2 3
Then your connectionStrings.config file only needs to change between environments, and can contain specific settings. It holds the contents of the element you're referring to, so it looks like this: ?
1 2 3 4
Another way I've seen this done is to have differently named connection strings config files for each environment (e.g. dev.config, staging.config, production.config). That allows you to check them all in to source control and not worry about getting files with the same name but different contents mixed up, but the tradeoff is that your Web.config in each environment needs to be updated to point to the right config source. So, this is a handy trick, but isn't quite perfect. A better option is to use Web.config File Transformations.
It's really easy to use - your main Web.config has the base settings for your site, and whenever you build, the transforms for the appropriate build configuration (e.g. Debug or Release) are automatically applied. If you had a Test database that you wanted to use by default, but wanted your Release builds to run against the Production database, you could set it up so that your base Web.config connection string points to the Test Database connection string, like this: ?
1 2 3 4
?
Then your Web.Release.config overwrites that to point at the Production database, like this:
<?xml version="1.0"?>
2 3 4 5 6 7 8
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <connectionStrings> <add name="ApplicationServices" connectionString="[ProductionDatabase]" xdt:Transform="Replace" xdt:Locator="Match(name)"/> </connectionStrings> </configuration>
The syntax is pretty straightforward, but you don't need to worry about that because the comments in the Web.Release.config file already show how to do that. To be clear: unlike the other examples, this is something that happens at build time, not runtime. I recently ran into an issue where I wanted to deploy something to AppHarbor and wanted to switch between a local SQL Compact database and the hosted database server, and Web.config Transforms worked just great there. There's a lot more to talk about with Web.config Transforms that's beyond the scope here, such as:
You can create as many build configurations as you want, with different transforms for each configuration. This makes it simple to switch between different settings in your development environment - say, switching between several development databases or other application settings. You can use the configuration transformation system with any XML file using the SlowCheetah Visual Studio extension. Scott Hanselman's written a post with more information on that here: SlowCheetah - Web.config Transformation Syntax now generalized for any XML configuration file Sayed (the Microsoft developer who's worked on both Web.config Transforms and the SlowCheetah extension) has also built a Package Once Publish AnywhereNuGet package which allows you to defer running the transforms until later, using a PowerShell command. That means you can build one Web Deployment Package with all the transforms included, and run them when you're going to deploy to a specific environment.
Web.config File Transformation section in the Web Application Project Deployment Overview Web.config Transformation Syntax for Web Application Project Deployment Scott Hanselman: Web Deployment Made Awesome: If You're Using XCopy, You're Doing It Wrong
referenced via configSource), then toggling the restartOnExternalChanges property and showing the differences in operation.
Summary
The ASP.NET Configuration system does quite a bit - I didn't even mention big topics like using the API for reading and writing values to both local and external config files or creating custom configuration sections. This post focuses on one aspect: getting things done by understanding and leveraging inheritance and overrides. Hopefully this gives you both some new tools for effectively handling configuration and some background that helps in troubleshooting when configuration is working as you'd like. Are there any essential tips that I missed?
ASP.NET - Configuration
Advertisements
The behavior of an ASP.Net application is affected by different settings in the configuration files:
machine.config web.config
The machine.config file contains default and the machine-specific value for all supported settings. The machine settings are controlled by the system administrator and applications are generally not given access to this file. An application however, can override the default values by creating web.config files in its roots folder. The web.config file is a subset of the machine.config file. If the application contains child directories, it can define a web.config file for each folder. Scope of each configuration file is determined in a hierarchical top-down manner. Any web.config file can locally extend, restrict or override any settings defined on the upper level. Visual Studio generates a default web.config file for each project. An application can run without a web.config file, however, you cannot debug an application without a web.config file. The following figure shows the Solution Explorer for the sample example used in the web services tutorial:
In this application there are two web.config files for two projects i.e., the web service and the web site calling the web service. The web.config file has the configuration element as the root node. Information inside this element is grouped into two main areas: the configuration section-handler declaration area, and the configuration section settings area. The following code snippet shows the basic syntax of a configuration file:
<configuration> <!-- Configuration section-handler declaration area. --> <configSections> <section name="section1" type="section1Handler" /> <section name="section2" type="section2Handler" /> </configSections> <!-- Configuration section settings area. --> <section1> <s1Setting1 attribute1="attr1" /> </section1> <section2> <s2Setting1 attribute1="attr1" /> </section2> <system.web> <authentication mode="Windows" /> </system.web> </configuration>
The configuration section handlers are contained within the <configSections> tags. Each configuration handler specifies name of a configuration section, contained within the file, which provides some configuration data. It has the following basic syntax:
Clear - it removes all references to inherited sections and section groups. Remove - it removes a reference to an inherited section and section group. Section - it defines an association between a configuration section handler and a configuration element. Section group - it defines an association between a configuration section handler and a configuration section.
<configuration> <appSettings> <add key="appISBN" value="0-273-68726-3" /> <add key="appBook" value="Corporate Finance" /> </appSettings> </configuration>
<connectionStrings> <add name="ASPDotNetStepByStepConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=E:\\projects\datacaching\ / datacaching\App_Data\ASPDotNetStepByStep.mdb" providerName="System.Data.OleDb" /> <add name="booksConnectionString"
<system.web> <anonymousIdentification> <authentication> <authorization> <browserCaps> <caching> <clientTarget> <compilation> <customErrors> <deployment> <deviceFilters> <globalization> <healthMonitoring> <hostingEnvironment> <httpCookies> <httpHandlers> <httpModules> <httpRuntime> <identity> <machineKey> <membership> <mobileControls> <pages> <processModel> <profile> <roleManager> <securityPolicy> <sessionPageState> <sessionState> <siteMap> <trace> <trust> <urlMappings> <webControls> <webParts> <webServices> <xhtmlConformance> </system.web>
The following table provides brief description of some of common sub elements of thesystem.web element:
anonymousIdentification:
This is required to identify users who are not authenticated when authorization is required.
authentication:
It configures the authentication support. Basic syntax:
authorization
It configures the authorization support.Basic syntax:
caching:
Configures the cache settings.Basic syntax:
customErrors:
Defines custom error messages. Basic syntax:
deployment:
Defines configuration settings used for deployment. Basic syntax:
hostingEnvironment:
Defines configuration settings for hosting environment.Basic syntax:
/>
identity:
Configures the identity of the application. Basic syntax:
machineKey:
Configures keys to use for encryption and decryption of Forms authentication cookie data. It also allows configuring a validation key that performs message authentication checks on view-state data and Forms authentication tickets. Basic syntax:
<machineKey validationKey="AutoGenerate,IsolateApps" [String] decryptionKey="AutoGenerate,IsolateApps" [String] validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name] decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name] />
membership:
This configures parameters of managing and authenticating user accounts.Basic syntax:
pages:
Provides page-specific configurations. Basic syntax:
<pages asyncTimeout="number" autoEventWireup="[True|False]" buffer="[True|False]" clientIDMode="[AutoID|Predictable|Static]" compilationMode="[Always|Auto|Never]" controlRenderingCompatibilityVersion="[3.5|4.0]" enableEventValidation="[True|False]" enableSessionState="[True|False|ReadOnly]" enableViewState="[True|False]" enableViewStateMac="[True|False]" maintainScrollPositionOnPostBack="[True|False]" masterPageFile="file path" maxPageStateFieldLength="number" pageBaseType="typename, assembly"
pageParserFilterType="string" smartNavigation="[True|False]" styleSheetTheme="string" theme="string" userControlBaseType="typename" validateRequest="[True|False]" viewStateEncryptionMode="[Always|Auto|Never]" > <controls>...</controls> <namespaces>...</namespaces> <tagMapping>...</tagMapping> <ignoreDeviceFilters>...</ignoreDeviceFilters> </pages>
profile:
Configures user profile parameters. Basic syntax:
<profile enabled="true|false" inherits="fully qualified type reference" automaticSaveEnabled="true|false" defaultProvider="provider name"> <properties>...</properties> <providers>...</providers> </profile>
roleManager:
Configures settings for user roles. Basic syntax:
<roleManager cacheRolesInCookie="true|false" cookieName="name" cookiePath="/" cookieProtection="All|Encryption|Validation|None" cookieRequireSSL="true|false " cookieSlidingExpiration="true|false " cookieTimeout="number of minutes" createPersistentCookie="true|false" defaultProvider="provider name" domain="cookie domain"> enabled="true|false" maxCachedResults="maximum number of role names cached" <providers>...</providers> </roleManager>
securityPolicy:
Configures the security policy. Basic syntax:
urlMappings:
Defines the mappings for hiding the actual URL and providing a more user friendly URL. Basic syntax:
webControls:
It provides the name of shared location for client scipts. Basic syntax:
webServices:
This configures the web services.