skip to content

Static Files & Assets

Serving files from wwwroot with UseStaticFiles, or with MapStaticAssets, which since .NET 9 fingerprints and precompresses them at build. Interviewers ask about cache headers and SPA fallbacks.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

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?

level: juniorimportance: must knowfreq 70%

answer

  1. web root, not content root
  2. WebRootPath: {content root}/wwwroot
  3. GET or HEAD only
  4. FileExtensionContentTypeProvider lookup
  5. ServeUnknownFileTypes defaults to false

basics

~20 s

UseStaticFiles 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 lines
csharp
using 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

for a junior

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.

for a middle

Walk through the checks: endpoint already selected, GET or HEAD, RequestPath, the content-type lookup and file existence, and say what the response carries.

for a senior

Diagnose a 404 for a file that exists, choose a mapping over ServeUnknownFileTypes, and explain how a second UseStaticFiles exposes another folder safely.

for a principal

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.
open as a page

In ASP.NET Core 10, what does app.MapStaticAssets() do that app.UseStaticFiles() does not, and when do you still need UseStaticFiles?

level: middleimportance: must knowfreq 58%

basics

~20 s

MapStaticAssets serves wwwroot files as endpoints from a build-time manifest, with fingerprinted URLs, precompressed copies (Brotli added at publish), content-hash ETags and long-lived caching headers. UseStaticFiles is still needed for files the build never saw.

open as a page

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

level: middleimportance: should knowfreq 35%

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.

open as a page

In an ASP.NET Core 10 app hosting a single-page app, what does app.MapFallbackToFile("index.html") do, and which requests does it not catch?

level: middleimportance: should knowfreq 40%

basics

~10 s

MapFallbackToFile adds a lowest-priority GET/HEAD endpoint with the pattern {*path:nonfile} that serves index.html through the static file middleware. It skips URLs whose last segment contains a dot, other methods, and anything another endpoint matched.

open as a page

On an ASP.NET Core 10 cycling-club site, how would you serve a members-only downloads folder so that anonymous visitors cannot fetch its files?

level: seniorimportance: should knowfreq 45%

basics

~10 s

Keep the files outside wwwroot, then either serve them with a second UseStaticFiles placed after UseAuthorization under a fallback policy requiring authenticated users, or through an endpoint with RequireAuthorization that returns TypedResults.PhysicalFile.

open as a page