Static Files
Images, CSS, JavaScript bundles, fonts and downloadable files are static files: the server sends them exactly as they are on disk. ASP.NET Core does not serve anything from disk by default — you opt in with a middleware or endpoint, and only files under the web root (by default the wwwroot folder) are exposed.
MyApp/
Program.cs
appsettings.json
wwwroot/ ← web root: public files
css/site.css → /css/site.css
js/app.js → /js/app.js
images/logo.png → /images/logo.png
index.html → /index.htmlNote: Files outside
wwwroot—appsettings.json, your.csfiles, the compiled.dll— can never be downloaded through static-file handling. Keep it that way: never put secrets inwwwroot.
Two ways to serve them in .NET 9
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
// Option A (new in .NET 9, used by the templates): build-time optimized assets
app.MapStaticAssets();
// Option B (classic middleware): serves whatever is in wwwroot at runtime
// app.UseStaticFiles();
app.MapRazorPages();
app.Run();UseStaticFiles() |
MapStaticAssets() (.NET 9) |
|
|---|---|---|
| Kind | Middleware — runs early in the pipeline | Endpoints — added to routing |
| File list | Read from disk at request time | Known at build/publish time |
| Compression | None (unless you add it) | gzip + Brotli versions created at publish |
| Caching | ETag + Last-Modified |
Content-hash ETags, long-lived caching for fingerprinted files |
| Best for | Files that appear at runtime (uploads), custom folders | Your app's own CSS/JS/images |
You can use both: MapStaticAssets for the app's assets and UseStaticFiles for, say, a folder of user uploads.
$ curl -s -I localhost:5000/css/site.css
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/appsettings.jsonHTTP/1.1 200 OK
Content-Length: 1832
Content-Type: text/css
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Accept-Ranges: bytes
Cache-Control: no-cache
ETag: "kq3l8X1yLKp0vJmFh0ZbK2mE0t3c0wN9hB7xqv5uR2A="
Last-Modified: Wed, 15 Oct 2026 14:22:10 GMT
Vary: Accept-Encoding
404
Content types
The browser needs a correct Content-Type to treat a file as CSS, JavaScript or an image. The middleware picks it from the file extension using FileExtensionContentTypeProvider, which knows several hundred mappings. Unknown extensions are not served at all (404) — a safety default so random files aren't exposed by accident. The idea in miniature:
using System;
using System.Collections.Generic;
using System.IO;
var contentTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
[".html"] = "text/html",
[".css"] = "text/css",
[".js"] = "text/javascript",
[".json"] = "application/json",
[".png"] = "image/png",
[".svg"] = "image/svg+xml",
[".woff2"] = "font/woff2",
};
foreach (var path in new[] { "/css/site.css", "/images/Logo.PNG", "/js/app.js", "/data/report.xyz" })
{
string ext = Path.GetExtension(path);
Console.WriteLine(contentTypes.TryGetValue(ext, out var type)
? quot;{path,-18} 200 {type}"
: quot;{path,-18} 404 (unknown extension)");
}/css/site.css 200 text/css
/images/Logo.PNG 200 image/png
/js/app.js 200 text/javascript
/data/report.xyz 404 (unknown extension)
Add your own mapping when needed:
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".webmanifest"] = "application/manifest+json";
app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider });Staying inside the web root
A request like /../appsettings.json tries to climb out of wwwroot. The file provider normalizes the requested path and refuses anything that resolves outside the root. You can see the check with plain System.IO:
using System;
using System.IO;
string webRoot = Path.GetFullPath("/srv/myapp/wwwroot") + Path.DirectorySeparatorChar;
foreach (var request in new[] { "css/site.css", "images/../js/app.js", "../appsettings.json", "../../etc/passwd" })
{
string full = Path.GetFullPath(Path.Combine(webRoot, request));
bool allowed = full.StartsWith(webRoot, StringComparison.Ordinal);
Console.WriteLine(quot;{request,-22} -> {full,-34} {(allowed ? "serve" : "BLOCK")}");
}css/site.css -> /srv/myapp/wwwroot/css/site.css serve
images/../js/app.js -> /srv/myapp/wwwroot/js/app.js serve
../appsettings.json -> /srv/myapp/appsettings.json BLOCK
../../etc/passwd -> /srv/etc/passwd BLOCK
Default documents and other folders
app.UseDefaultFiles(); // "/" → "/index.html" (also default.htm, index.htm …) — must come BEFORE UseStaticFiles
app.UseStaticFiles();
// Serve a second folder under a URL prefix
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "uploads")),
RequestPath = "/files",
OnPrepareResponse = ctx =>
ctx.Context.Response.Headers.CacheControl = "public,max-age=3600"
});UseDefaultFiles only rewrites the URL; UseStaticFiles then actually sends the file — so the order matters. For single-page apps (React, Angular, Vue) add app.MapFallbackToFile("index.html") so that unknown client-side routes like /dashboard/settings return the SPA's shell.
Cache busting
Browsers cache static files. When you deploy a new site.css, users may keep the old one. Two fixes:
- In Razor,
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />appends?v=<hash of the file>, so the URL changes whenever the content does. - In .NET 9 with
MapStaticAssets, use@Assets["css/site.css"](or the<ImportMap />component) to get a fingerprinted URL such as/css/site.k3j9x2lq.cssthat can be cached for a year.
Tip: Static file middleware does not check authorization. If a file should require login, don't put it in
wwwroot— serve it from an endpoint that callsResults.File(...)after checking the user.
Test yourself
Which folder is the default web root for static files?
- wwwroot
- public
- static
- bin
Why must UseDefaultFiles() be called before UseStaticFiles()?
- It compresses the files first
- It only rewrites
/to/index.html; the static file middleware then serves it - It registers the MIME types
- It is not required — order never matters for middleware
What does the static file middleware do with a file whose extension it doesn't recognize?
- Serves it as text/plain
- Serves it as application/octet-stream
- Returns 404 (not served)
- Throws an exception