DefaultFiles and FileServer in ASP.NET Core

Wednesday, October 25, 2017

The DefaultFiles middleware of ASP.NET Core is often misunderstood.

app.UseDefaultFiles();

The DefaultFiles middleware by itself will not serve any files. DefaultFiles will only re-write the request Path value to match a file name, if the request points to a directory where a default file exists.

You still need the StaticFiles middleware to serve the default file.

app.UseDefaultFiles();
app.UseStaticFiles();

It’s also important to know that DefaultFiles, like StaticFiles, will work in the web root path by default (wwwroot). If you want both pieces of middleware to work with a different (or second) folder of files, you’ll need to give both pieces of middleware a file provider that points to the folder.

var clientPath = Path.Combine(env.ContentRootPath, "client");
var fileprovider = new PhysicalFileProvider(clientPath);
app.UseDefaultFiles(new DefaultFilesOptions
{
    DefaultFileNames = new [] { "foo.html" },
    FileProvider = fileprovider
});

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = fileprovider              
});

In most cases, the middleware you want to use for these scenarios is the FileServer middleware, which combines DefaultFiles and StaticFiles.

var clientPath = Path.Combine(env.ContentRootPath, "client");
var fileprovider = new PhysicalFileProvider(clientPath);
var fileServerOptions = new FileServerOptions();
fileServerOptions.DefaultFilesOptions
                 .DefaultFileNames = new[] { "foo.html" };
fileServerOptions.FileProvider = fileprovider;

app.UseFileServer(fileServerOptions);

Comments
gravatar Brian Wells Thursday, October 26, 2017
I really appreciate your material, Scott -- and born editor that I am, feel free to delete this comment as soon as you fix your typo from defaut to default -- and, speaking for myself, I'll now return to your pluralsight tutorial....
gravatar Scott Friday, October 27, 2017
Ooops, in the title, too! Thank you for catching that
Comments are closed.