Skip to content

Static Files on IIS

Chris R edited this page Feb 8, 2017 · 1 revision

The Katana static file middleware can be used on both self-host (HttpListener) and web-host (SystemWeb). However, when running on SystemWeb/IIS, some additional configuration may be required.

IIS has a native static file module that is optimize to skip other portions of the pipeline if it sees file paths that do not match other handlers (e.g. not aspx). This means that the directory browser middleware is likely to work, but then the static file middleware may be bypassed in favor of the native static file module.

Workaround:

Here are two changes you need to make to ensure the static file middleware runs instead of the native static file module.

In your web.config add:

<configuration>
   <system.webServer>
      <modules runAllManagedModulesForAllRequests="true" />
   </system.webServer>
</configuration>

This tells IIS not to skip the managed Asp.Net modules even if the native static file module thinks it has a match.

Also, add the following stage marker AFTER your static file middleware (in namespace Microsoft.Owin.Extensions):

app.UseStageMarker(PipelineStage.MapHandler);

See the following article for more details about working with stage markers: http://www.asp.net/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline

Alternatives:

If you don't want to use the above approach, either of the following options should also work:

Configure the static file middleware so that the url path does not directly match the physical path.

app.UseFileServer(new FileServerOptions
{
  FileSystem = new PhysicalFileSystem(".\\public"),
  RequestPath = new PathString("/files"),
});

This causes requests for /files/myfile.txt to be mapped to .\public\myfile.txt, bypassing the native static file module's url matching.

The other alternative is to remove the native static file module, either via the IIS configuration page or the applicationhost.config file.