Iis – Shared hosting on IIS7. Not able to access resources with ‘StaticFileModule’ handlers

iisiis-7

I have directories for images and styles, with a Web.config file (using Orchard). In that Web.config there is a line causing a problem on my shared hosting (running fine in WebMatrix):

  <system.webServer>
    <handlers accessPolicy="Script,Read">
      <!--
      iis7 - for any request to a file exists on disk, return it via native http module.
      accessPolicy 'Script' is to allow for a managed 404 page.
      -->
      <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" preCondition="integratedMode" resourceType="File" requireAccess="Read" />
    </handlers>
  </system.webServer>

When I try to access any files from that directory I get a 500 page:

500 – Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.

When I delete the line

<add name="StaticFile" path="*" verb="*" modules="StaticFileModule" preCondition="integratedMode" resourceType="File" requireAccess="Read" />

it displays the resources.

How can I fix this problem without altering the Web.config file located in each directory containing files which are intended to be accessed directly?

Best Answer

I do not think you can (on Shared hosting, I mean).

The error clearly says: "Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'StaticFile". This means that there is already an entry with name="StaticFile" somewhere above in config hierarchy (in another web.config in a parent folder .. or, most likely, global web server config.

To solve it, you have to remove existing config line first. You have to add <remove name="StaticFile" /> line into your <handlers> section before adding your own handler, for example:

<system.webServer>
    <handlers accessPolicy="Script,Read">
        <remove name="StaticFile" />
        <!--
        iis7 - for any request to a file exists on disk, return it via native http module.
        accessPolicy 'Script' is to allow for a managed 404 page.
        -->
        <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" preCondition="integratedMode" resourceType="File" requireAccess="Read"/>
    </handlers>
</system.webServer>

If you would have full control over your server (which you do not, since you are on shared hosting) you could remove StaticFile handler from global IIS config ... but is it wise?? Adding the <remove...> line is a correct approach for both scenarios.