Chris Chris - 3 months ago 21
ASP.NET (C#) Question

Asp.net HttpModule in directory level web.config

I created a custom http module and want to add this module to the web config. The web application is a project that contains several "sub applications". A sub application is just a folder, and within that folder it has its own web.config. I'm doing this so each application has its own application related contents, stylesheets, configs etc.

Now I created a custom http module. When adding this to the root web.config, the module is working properly. When adding the http module config to the directory-level web.config (e.g. /Applications/MyApplication/web.config) the module is not initialized anymore. Even though the msdn states that the HttpModules config element is also working at directory level. Anyone knows how to solve this?

Answer

To echo Marvin Smit's comment, it seems that configuring <modules> under a <location> in web.config simply does not work - any modules specified in this fashion are NOT invoked.

What you can do is to specify the module at root level, and have it controlled by an appSetting, which can be hierarchically specified and overridden as required:

<configuration>


  <appSettings>
    <add key="UseCustomModule" value="false"/>
  </appSettings>


  <location path="MyFolder">
    <appSettings>
      <add key="UseCustomModule" value="true"/>
    </appSettings>
    <system.webServer>
      <modules>
        <!-- CANNOT add module at this level, hence the overridden appSetting -->
      </modules>
    </system.webServer>
  </location>

  <system.webServer>
    <modules>
      <add name="CustomnModule" type="MyApplication.CustomModule" />
    </modules>
  </system.webServer>

</configuration>

Then within the code for CustomModule:

    private static bool ModuleEnabled()
    {
        bool appSetting;
        if (!bool.TryParse(ConfigurationManager.AppSettings["UseCustomModule"], 
                           out appSetting))
            appSetting = false;

        return appSetting;
    }

ASP.NET will see to it that the appropriate value of UseCustomModule for our current location is the one we read.