In ASP.NET Core, how does app.UseStaticFiles() decide which file to serve for a request, and when does it pass the request on instead?
answer
- web root, not content root
- WebRootPath: {content root}/wwwroot
- GET or HEAD only
- FileExtensionContentTypeProvider lookup
- ServeUnknownFileTypes defaults to false
basics
~20 sUseStaticFiles maps the URL path onto the web root (wwwroot by default). For a GET or HEAD whose extension has a known content type, it streams the matching file and ends the request; anything else goes to the next middleware.
solid answer
~40 s`UseStaticFiles` adds `StaticFileMiddleware`, which reads through `IWebHostEnvironment.WebRootFileProvider`, a provider rooted at `WebRootPath`: `{content root}/wwwroot` unless `WebApplicationOptions.WebRootPath` names another folder. So `/js/app.js` maps to `wwwroot/js/app.js`. The middleware serves a file only when no endpoint has been selected yet, the method is GET or HEAD, the path is under its `RequestPath`, `FileExtensionContentTypeProvider` knows the extension, and the file exists. It then writes the file with `Content-Type`, `ETag`, `Last-Modified` and range support, and does not call the rest of the pipeline. If any check fails, it calls `next`, which usually ends in a 404. An unknown extension such as `.gpx` fails the lookup, so the right fix is a mapping rather than `ServeUnknownFileTypes`. One instance never reaches outside its provider; to expose another folder you add another `UseStaticFiles` with its own `FileProvider`.
code
csharp · 17 linesusing Microsoft.AspNetCore.StaticFiles;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// wwwroot/routes/loop.gpx returns 404 until .gpx has a content type
var types = new FileExtensionContentTypeProvider();
types.Mappings[".gpx"] = "application/gpx+xml";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = types,
OnPrepareResponse = ctx =>
ctx.Context.Response.Headers.CacheControl = "public, max-age=3600"
});
app.Run();go deeper
Know that only wwwroot is public, that the URL path maps onto it, and that UseStaticFiles answers the request itself when it finds the file.
Walk through the checks: endpoint already selected, GET or HEAD, RequestPath, the content-type lookup and file existence, and say what the response carries.
Diagnose a 404 for a file that exists, choose a mapping over ServeUnknownFileTypes, and explain how a second UseStaticFiles exposes another folder safely.
Weigh what the app should serve itself against what belongs on a CDN or reverse proxy, and how the public surface of the web root is reviewed.
## The web root and the content root ASP.NET Core keeps two folders apart. The **content root** (`IWebHostEnvironment.ContentRootPath`) is the app's base directory, where `appsettings.json`, Razor views and the project's other files live. The **web root** (`IWebHostEnvironment.WebRootPath`) is the only folder meant to be public. When nothing configures it, the host uses `{content root}/wwwroot` if that folder exists. If it does not exist, `WebRootFileProvider` is a `NullFileProvider` and the static file middleware logs a warning that the web root was not found. The provider is chosen once at startup, so a `wwwroot` folder created while the app is running is not served until the app restarts; when `WebRootPath` is set explicitly, the host creates the folder if it is missing. To use a different folder, pass it when the builder is created: ```csharp var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args, WebRootPath = "public" }); ``` Changing it afterwards with `builder.WebHost.UseWebRoot(...)` throws a `NotSupportedException` whose message tells you to use `WebApplicationOptions` instead. ## The checks UseStaticFiles runs on each request `app.UseStaticFiles()` adds `StaticFileMiddleware`. It serves a file only when every check below passes: 1. **No endpoint is selected yet.** If routing has already picked an endpoint with a request delegate, the middleware steps aside. 2. **The method is GET or HEAD.** A POST to `/images/logo.png` goes straight to the next middleware, even though the file exists. 3. **The path is under `RequestPath`.** `RequestPath` is empty by default, so the URL path maps directly onto the web root: `/js/app.js` becomes `wwwroot/js/app.js`. 4. **The extension has a content type.** `FileExtensionContentTypeProvider` ships with almost 400 extension-to-MIME mappings. An unknown extension fails here unless `ServeUnknownFileTypes` is `true`. 5. **The file exists** in the configured `IFileProvider`. `RequestPath` is how one middleware instance serves a folder under a URL prefix: with `RequestPath = "/media"`, a request for `/media/logo.png` looks up `logo.png` in that instance's provider, and requests outside `/media` are ignored by it. When all five pass, the middleware writes the file and returns **without calling `next`**, so middleware registered after it never sees that request. When any check fails, it calls `next`; in an app with no matching endpoint the request ends as a 404. The current MVC, Razor Pages and Blazor templates call `MapStaticAssets` for files known at build time. `UseStaticFiles` is not obsolete: it is still what serves files from other folders and files that appear at runtime. ## What the response carries | Header or behaviour | Sent by default? | |---|---| | `Content-Type` from the content-type provider | yes | | `Last-Modified`, and an `ETag` computed from the file's timestamp and length | yes | | `Accept-Ranges: bytes` and 206 partial responses | yes | | 304 for a matching `If-None-Match` or `If-Modified-Since` | yes | | `Cache-Control` | **no**: add it in `StaticFileOptions.OnPrepareResponse` | ## The .gpx trap: unknown extensions A cycling club drops GPS route files into `wwwroot/routes/`, and `GET /routes/loop.gpx` returns 404 although the file is there. `.gpx` is not in the default mapping table, so check 4 fails and the request is passed on. There are two ways out, and only one is safe: - **Add a mapping.** Create a `FileExtensionContentTypeProvider`, set `Mappings[".gpx"]`, and pass it as `StaticFileOptions.ContentTypeProvider`. Only that extension becomes servable. - **Set `ServeUnknownFileTypes = true`** with a `DefaultContentType`. The documentation calls this a security risk and discourages it, because every file in the folder becomes downloadable whatever its extension. Configure the provider once at startup: its `Mappings` dictionary is not safe for writes while requests are reading it. ## Serving a second folder Each `UseStaticFiles` call adds its own middleware instance with its own `StaticFileOptions`. To expose another folder, add a second call with a `FileProvider` and a `RequestPath`: ```csharp app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(builder.Environment.ContentRootPath, "media")), RequestPath = "/media" }); ``` `PhysicalFileProvider` refuses paths that climb above its root and, with its default `ExclusionFilters.Sensitive`, hides dot-prefixed, hidden and system files. ## What interviewers listen for - Only the web root is public; code and configuration in the content root are not served. - The checks in order, especially GET/HEAD only and the content-type lookup. - That the middleware **ends the request** when it serves a file, so later middleware does not run for it. - That it sends validators (`ETag`, `Last-Modified`) but no `Cache-Control` unless you add one. - That a mapping, not `ServeUnknownFileTypes`, is the fix for an unknown extension.
- How would you also serve files from a folder outside wwwroot, such as a media folder under the content root?Add a second `app.UseStaticFiles(new StaticFileOptions { ... })` whose `FileProvider` is a `PhysicalFileProvider` over `Path.Combine(builder.Environment.ContentRootPath, "media")` and whose `RequestPath` is `/media`. Each call is a separate middleware instance, so the default one keeps serving the web root while the new one serves `/media/...` from that folder.
- Why can't you change the web root with builder.WebHost.UseWebRoot in a WebApplication app?`WebApplicationBuilder` has already resolved host settings such as the content root, the environment and the web root by the time `builder.WebHost` exists. Its `ConfigureWebHostBuilder` throws a `NotSupportedException` when one of them changes and tells you to pass `WebApplicationOptions` to `WebApplication.CreateBuilder` instead, for example `WebRootPath = "public"`.
- UseStaticFiles serves every file in the project folder, including appsettings.json.
- Setting ServeUnknownFileTypes to true is the normal fix for a missing MIME type.
- UseStaticFiles is obsolete in ASP.NET Core 10 and must be replaced everywhere.
- The static file middleware adds a long Cache-Control header to every file by default.
- builder.WebHost.UseWebRoot changes the web root just like WebApplicationOptions.WebRootPath.