skip to content

In ASP.NET Core, what do UseDefaultFiles, UseFileServer and UseDirectoryBrowser each do, and why must UseDefaultFiles run before UseStaticFiles?

level: middleimportance: should knowfreq 35%

answer

  1. a rewriter, not a server
  2. default.htm, default.html, index.htm, index.html
  3. RedirectToAppendTrailingSlash defaults to true
  4. EnableDirectoryBrowsing defaults to false
  5. AddDirectoryBrowser registers its services

basics

~20 s

UseDefaultFiles only rewrites a folder request such as / to its index file; UseStaticFiles, placed after it, serves the file. UseDirectoryBrowser lists folder contents, and UseFileServer combines default files, static files and, if enabled, directory browsing.

solid answer

~40 s

`UseDefaultFiles` is a URL rewriter: for a GET or HEAD to a folder, it looks for `default.htm`, `default.html`, `index.htm` and `index.html` in that order and rewrites `Request.Path` to the first one found. If the URL lacks a trailing slash it first answers with a 301 to add one, because `RedirectToAppendTrailingSlash` defaults to `true`. It never writes the file, so `UseStaticFiles` must come after it; placed before, the static files middleware sees `/`, finds no file and passes on, and the rewrite is wasted. `UseDirectoryBrowser` renders an HTML listing of a folder and relies on services that `AddDirectoryBrowser()` registers; browsing is off by default because it exposes file names. `UseFileServer` registers default files, optional directory browsing (`EnableDirectoryBrowsing` is `false` by default) and static files in the right order, sharing one `FileProvider` and `RequestPath`.

code

csharp · 16 lines
csharp
using Microsoft.Extensions.FileProviders;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDirectoryBrowser();
var app = builder.Build();

// Ride reports live outside wwwroot; browsing only on a developer machine
app.UseFileServer(new FileServerOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(builder.Environment.ContentRootPath, "ride-reports")),
    RequestPath = "/ride-reports",
    EnableDirectoryBrowsing = app.Environment.IsDevelopment()
});

app.Run();

go deeper

for a junior

Remember that UseDefaultFiles turns / into /index.html and that UseStaticFiles must come after it to actually send the file.

for a middle

Explain the default name list, the trailing-slash redirect, and exactly what UseFileServer registers and in which order.

for a senior

Keep directory browsing out of production, serve default documents correctly alongside MapStaticAssets, and debug a root URL that returns 404.

for a principal

Decide which folders an app should expose at all and how that decision is reviewed as files accumulate in them.

## Three helpers around the static file middleware The `Microsoft.AspNetCore.StaticFiles` package contains three middleware besides `StaticFileMiddleware`. Only one of them sends file bytes: | Call | Middleware | What it does | Default state | |---|---|---|---| | `UseDefaultFiles()` | `DefaultFilesMiddleware` | rewrites a folder URL to its default document | off until called | | `UseDirectoryBrowser()` | `DirectoryBrowserMiddleware` | renders an HTML listing of a folder | off until called; needs `AddDirectoryBrowser()` | | `UseStaticFiles()` | `StaticFileMiddleware` | writes the file | off until called | | `UseFileServer()` | registers the others | default files + optional browsing + static files | browsing disabled | ## UseDefaultFiles is a rewriter For a GET or HEAD whose path names a folder in its file provider, the web root by default (and when no endpoint has been selected yet), `DefaultFilesMiddleware`: 1. Checks that the folder exists in its `IFileProvider`. 2. Walks `DefaultFilesOptions.DefaultFileNames`, which by default is `default.htm`, `default.html`, `index.htm`, `index.html`, and stops at the first file that exists. 3. If the URL does not end in `/` and `RedirectToAppendTrailingSlash` is `true` (the default), answers with **301** to the same URL plus `/`, so relative links in the page resolve against the folder. 4. Otherwise rewrites `Request.Path`, for example from `/` to `/index.html`, and calls `next`. It never writes the file. The browser's address bar keeps the URL the user typed; only the server-side path changed. Like the static file middleware, it ignores POST and other methods and does nothing when routing has already selected an endpoint with a request delegate, so a mapped endpoint for `/` takes precedence over `index.html`. That is why the order matters: - `UseDefaultFiles()` then `UseStaticFiles()`: the rewrite happens first, and the static file middleware serves `/index.html`. - `UseStaticFiles()` then `UseDefaultFiles()`: the static file middleware sees `/`, finds no file and passes on; the rewrite happens afterwards, and in a pipeline with nothing else to serve the new path the visitor gets a 404. To use another name, clear the list and add yours: ```csharp var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("welcome.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); ``` ## Default documents with MapStaticAssets `MapStaticAssets` maps each asset to its own route and does not serve default documents. With minimal hosting, routing runs at the start of the pipeline, so by the time `UseDefaultFiles` rewrites `/` to `/index.html`, endpoint matching has already happened and no asset endpoint is selected. The documentation therefore prescribes `UseDefaultFiles()`, then `UseStaticFiles()`, then `MapStaticAssets()`; without the `UseStaticFiles` call, `/` returns 404. ## Directory browsing `UseDirectoryBrowser` answers a folder request with an HTML page listing its files and sub-folders. Its `DirectoryBrowserOptions` share the same `FileProvider` and `RequestPath` shape as the other two, and its `Formatter` property accepts an `IDirectoryFormatter` if the default HTML listing is not what you want. It is **off unless you call it**, and the documentation recommends keeping it off in production: - It reveals file names you never linked to, such as backups or exports left in the folder. - Everything listed is usually downloadable, because the static file middleware serves the same folder. - It needs `builder.Services.AddDirectoryBrowser()`, which registers the services the middleware depends on, including an `HtmlEncoder`. ## UseFileServer bundles them `UseFileServer` takes a `FileServerOptions` whose three inner option objects share one `FileProvider` and `RequestPath`. It adds, in this order: 1. `UseDefaultFiles` when `EnableDefaultFiles` is `true` (the default); 2. `UseDirectoryBrowser` when `EnableDirectoryBrowsing` is `true` (the default is `false`); 3. `UseStaticFiles`, always. So `app.UseFileServer()` gives default documents plus static files, and `app.UseFileServer(enableDirectoryBrowsing: true)` adds browsing too, which still requires `AddDirectoryBrowser()`. ## What interviewers listen for - `UseDefaultFiles` rewrites, `UseStaticFiles` serves, so the rewriter comes first. - The default list of four names and the trailing-slash redirect. - That `UseFileServer` does not browse directories unless asked. - That directory browsing is a disclosure risk, kept off in production. - That `MapStaticAssets` needs `UseDefaultFiles` plus `UseStaticFiles` to answer `/` with `index.html`.

  • A request for /ride-reports (no trailing slash) hits UseDefaultFiles and the folder holds index.html. What does the client get?
    A 301 redirect to `/ride-reports/`, because `RedirectToAppendTrailingSlash` defaults to `true` and a default file exists. The follow-up request ends in a slash, so it is rewritten to `/ride-reports/index.html` and served by the static file middleware. Set the option to `false` to rewrite without the redirect, at the cost of relative links resolving against the parent folder.
  • Why does the documentation call UseDefaultFiles with MapStaticAssets alone a 404 for the site root?
    `MapStaticAssets` does not map `/` to `index.html`. With minimal hosting, routing has already run when `UseDefaultFiles` rewrites the path, so no asset endpoint is selected for the new path. Adding `UseStaticFiles` after `UseDefaultFiles` lets the middleware serve the rewritten `/index.html`.

UseDefaultFiles is a club's front desk that writes 'room: index.html' on a visitor's slip when they just ask for the clubhouse; the steward further down the corridor, UseStaticFiles, actually takes them there. Put the steward before the desk and the visitor walks past him with no room number, so nobody takes them anywhere.

  • UseDefaultFiles serves index.html itself, so UseStaticFiles isn't needed after it.
  • Directory browsing is switched on for wwwroot by default.
  • app.UseFileServer() turns on directory browsing unless you pass false.
  • MapStaticAssets serves wwwroot/index.html for a request to the site root.
  • UseDefaultFiles changes the URL shown in the browser to /index.html.