skip to content

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%

answer

  1. build-time manifest, not a folder scan
  2. {app}.staticwebassets.endpoints.json
  3. SHA-256 fingerprint in the file name
  4. gzip at build, gzip + Brotli at publish
  5. WithStaticAssets and asp-append-version

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.

solid answer

~40 s

In ASP.NET Core 10, `MapStaticAssets` reads the `{app}.staticwebassets.endpoints.json` manifest the build writes and registers one endpoint per asset. At build or publish each file gets a SHA-256 fingerprint, a fingerprinted URL and precompressed copies (gzip at build, gzip and Brotli at publish), so at runtime it negotiates `Content-Encoding`, sends content-hash `ETag`s and marks fingerprinted URLs `immutable`. Because they are endpoints, authorization metadata applies to them. `.WithStaticAssets()` on `MapControllerRoute` or `MapRazorPages` lets `asp-append-version` emit the fingerprinted URL. You still need `UseStaticFiles` for anything outside the manifest: uploads written at runtime, folders served through another `FileProvider`, default documents, directory browsing, `OnPrepareResponse` headers, custom content-type mappings, and assets excluded with `StaticWebAssetEndpointExclusionPattern`.

code

csharp · 18 lines
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();

// Ride photos uploaded at runtime are not in the build manifest
app.UseStaticFiles();

app.MapStaticAssets();
app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}")
    .WithStaticAssets();

app.Run();

go deeper

for a junior

Recall that newer templates call MapStaticAssets, that it fingerprints and precompresses files at build time, and that UseStaticFiles still exists.

for a middle

Explain the manifest, the endpoint per asset, gzip at build and Brotli at publish, content-hash ETags, and what WithStaticAssets and asp-append-version do.

for a senior

Spot the production cases MapStaticAssets cannot cover, such as runtime uploads, large collections and other folders, and combine it with UseStaticFiles deliberately.

for a principal

Judge whether build-time asset handling in the app is enough or a CDN should own delivery, and what that means for cache invalidation across deploys.

## Two ways to serve the web root `UseStaticFiles` is middleware: on every request it looks at the URL, checks the extension, and reads the file from the web root as it is on disk at that moment. `MapStaticAssets`, added in .NET 9 and called by the ASP.NET Core 10 MVC, Razor Pages and Blazor templates, works the other way round: the **build** decides what the static assets are and how to serve them, and the app only replays that decision. | | `UseStaticFiles` | `MapStaticAssets` | |---|---|---| | Source of truth | the folder at request time | the build-time manifest | | Shape | middleware | one endpoint per asset | | Compression | none by itself | precompressed gzip and Brotli copies | | URL versioning | `?v=` query from `asp-append-version` | fingerprint in the file name | | `ETag` | file timestamp and length | content hash | | Caching header | none unless you add one | from the manifest; `immutable` on fingerprinted URLs | | Files added at runtime | served | not served after publish | ## What the build and publish produce 1. The static web assets step discovers the files under `wwwroot` (plus those of referenced Razor class libraries and files linked into `wwwroot`). 2. Each file gets a **fingerprint**: a Base64-encoded SHA-256 hash of its content. The default fingerprint pattern inserts it before the extension, so `ride-map.js` is also exposed under a fingerprinted name. 3. Compressible files get precompressed copies: **gzip during build, gzip and Brotli during publish**. Images and fonts that are already compressed are skipped. 4. Everything is written to `{AssemblyName}.staticwebassets.endpoints.json` in the output folder: routes, content types, `ETag`s, caching headers and the compressed variants. At startup `MapStaticAssets` locates that manifest via `IHostEnvironment.ApplicationName` under `AppContext.BaseDirectory` and throws an `InvalidOperationException` if it is missing. You can pass a different manifest path as its argument; a relative path is resolved against `AppContext.BaseDirectory`. Calling it twice with the same manifest returns the existing builder rather than registering the endpoints again. ## What happens at runtime - Every asset is a **route endpoint** with GET/HEAD metadata and an order of -100, so it is preferred over an ordinary route that matches the same URL. - Endpoint selection picks the precompressed variant that matches the request's `Accept-Encoding`; no compression work happens per request. - The `ETag` is the content hash, so a conditional request gets a 304 only when the content really is unchanged, even if the file was copied and its timestamp changed during deployment. - A fingerprinted URL carries `immutable` and a long `max-age`, so a browser does not ask for it again; a new build produces a new URL. - Because assets are endpoints, endpoint metadata applies. An app with an authorization fallback policy must add `AllowAnonymousAttribute` metadata to them to keep them public. ## Linking to the fingerprinted URL A fingerprint helps only if pages link to it: - **MVC and Razor Pages:** chain `.WithStaticAssets()` onto `MapControllerRoute` or `MapRazorPages`. It adds the asset collection to those endpoints (not to `[ApiController]` endpoints), and the `script`, `link` and `img` tag helpers with `asp-append-version="true"` then emit the fingerprinted URL. Without it they fall back to a `?v=` query string. - **Blazor:** `@Assets["app.css"]` and the `<ImportMap />` component resolve names through the same collection. ## When UseStaticFiles is still needed The manifest only knows what existed at build time, so `UseStaticFiles` remains the tool for: - files written at runtime, such as ride photos uploaded into `wwwroot/uploads`; - folders exposed through another `FileProvider`, and files in a custom `WebRootPath` the build never saw; - default documents (`UseDefaultFiles` must be followed by `UseStaticFiles`) and directory browsing; - per-response headers through `OnPrepareResponse` and custom extension mappings; - very large collections (around a thousand files or more), where the eagerly loaded metadata costs memory. Exclude them with the `StaticWebAssetEndpointExclusionPattern` MSBuild property and let `UseStaticFiles` serve them. ## Local runs versus a published app When the app runs from **build output** (`dotnet run`), `MapStaticAssets` enables a development handler: it rewrites `Cache-Control` to `no-cache` unless `EnableStaticAssetsDevelopmentCaching` is `true`, picks up edited files, and serves files added after the build through a fallback that logs a warning (`DisableStaticAssetNotFoundRuntimeFallback` turns it off). A **published** app serves the manifest and nothing else, which is why an upload folder that worked locally can return 404 in production.

  • Why might a site with thousands of icon files keep some of them out of MapStaticAssets?
    `MapStaticAssets` eagerly loads the manifest metadata for every asset to support compression, caching and fingerprinting, which costs memory. For rarely requested files that cost may not pay off, so you exclude them with the `StaticWebAssetEndpointExclusionPattern` MSBuild property (keeping `$(StaticWebAssetEndpointExclusionPattern)` in the value) and serve them with `UseStaticFiles` instead, without fingerprints or precompression.
  • Why do the caching headers differ between dotnet run and the published site?
    Running from build output enables `MapStaticAssets`' development handler, which rewrites `Cache-Control` to `no-cache` so edited files show up, removes integrity values and serves files added after the build. Setting `EnableStaticAssetsDevelopmentCaching` to `true` keeps the manifest's headers. A published app uses the publish manifest as is.
  • What happens at startup if the static web assets manifest is missing?
    `MapStaticAssets` builds the path `{ApplicationName}.staticwebassets.endpoints.json` under `AppContext.BaseDirectory`, or uses the path you pass, and throws an `InvalidOperationException` saying the static resources manifest was not found. That usually means the app was copied without its build output or the application name differs from the assembly that produced the manifest.

UseStaticFiles is a librarian who walks to the shelf every time you ask for a book; MapStaticAssets is a printed catalogue made at closing time, with each book already copied, shrink-wrapped and labelled. The catalogue is fast, but a book shelved after the catalogue was printed is not in it.

  • MapStaticAssets scans wwwroot on every request just like UseStaticFiles does.
  • MapStaticAssets needs AddResponseCompression before it can send Brotli.
  • UseStaticFiles is deprecated in .NET 10, so every call should be deleted.
  • Chaining WithStaticAssets onto MapRazorPages maps the static asset endpoints by itself.
  • MapStaticAssets fingerprints files by adding a ?v= query string to the URL.

Assumes ASP.NET Core 10; MapStaticAssets and WithStaticAssets arrived in .NET 9 and are what the 10.0 MVC, Razor Pages and Blazor templates call, while UseStaticFiles is not obsolete.