Richard Szalay

Monday, January 28, 2008

Preventing application configuration inheritance in ASP.NET

It's an extremely common problem: you create a virtual directory to house a supporting application, but accessing it throws an exception because it is trying to initialise the httpmodules/httphanders from the root application. Attempting to <clear /> them doesn't work because the clear happens after they are added, which means they need to exist in order to remove them.

Thankfully there is a solution. Introduced in .NET 2.0, the SectionInformation.InheritInChildApplications property, when set to false, stops the runtime from even attempting to load anything from that location when in a child application (like a virtual directory).

Now, as SectionInformation maps directly to the <location> configuration element, it means the offending sections will need to be wrapped in a <location>. When referring to the root application, you can either leave out the path attribute or assign it to "."

What is strange is that the inheritInChildApplications attribute is not document on the location Element MSDN page, or is it in the schema that is included in VS.NET. This would explain why its existence is not common knowledge

For clarity, I have modified the default web.config template to include the change

<?xml version="1.0"?>

<configuration>

  <appSettings/>
  <connectionStrings/>

  <location inheritInChildApplications="false">
    <system.web>
      <!-- 
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
      <compilation debug="true" />

      <!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
      <authentication mode="Windows" />
      <!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    </system.web>
  </location>
</configuration>

Labels: ,