How to apply different configuration settings in web.config to specific pages and folders in ASP.NET website?

 Copyright © 2007-2012 www.AspDotNetFaq.com

Your ASP.Net application can have many pages and subdirectories and very often you need to apply different configuration settings to those application resources in your web.config file.

One way to apply specific setting to separate folders via the another web.config file placed inside those folders, because each folder fo the application ca have its own web.config file.

Another way is to apply the specific settings to some folders and files in the main web.config file that is placed in the root of the ASP.NET web application.

You can do this easily by adding the <location> tag to your root web.config file and setting its path attribute to the resource (page or subfolder) you want to configure, like this:


  <system.web>

    <customErrors mode="On"></customErrors>
  </system.web>

     
     ....

  <location path="CustomErrorsOn">

    <system.web>

      <customErrors mode="On">
        <error statusCode="404" redirect="~/ErrorPages/Error404.aspx"></error>
      </customErrors>     

    </system.web>

  </location>

 

  <location path="CustomErrorsOff">

    <system.web>

      <customErrors mode="Off"></customErrors>

    </system.web>

  </location>


In this example, we first switch on custom errors for the whole application, and then we use the location tag to set different customErrors settings to different subdirectories of web application.

Folder "CustomErrorsOn" here has custom errors switched on  and has a redirect to specific page when 404 error occurs, while folder "CustomErrorsOff has custom errors switched off.

This approach can also be used to set other important settings like UrlRewrite mappings, HttpHandlers, Authentication settings etc.


 Copyright © 2007-2012 www.AspDotNetFaq.com