Skip to content

4.10 — wwwroot and Static Files

← Roadmap · Section: 4. Fundamentals and Application Startup Prev: 4.9 Kestrel vs IIS vs HTTP.sys · Next: 4.11 Project structure

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

Static files are files served exactly as they are on disk — images, CSS, JavaScript, PDFs. No code runs to produce them.

  • Only the wwwroot folder is served, and only if you call app.UseStaticFiles(). Nothing else in your project is reachable.
  • Anything you put in wwwroot is public. There is no authentication on it by default.
  • Register the middleware early in the pipeline, so image requests do not run authentication and routing for nothing.

Definitions

Term What it is What it means
Static file a file served as-is Returned byte-for-byte from disk. No processing, no code execution.
Web root a folder wwwroot by default. The only folder publicly served.
Content root a folder The app's base directory, where appsettings.json and DLLs live. Not served.
UseStaticFiles() a middleware method Enables serving files from the web root. Without it, nothing is served.
UseFileServer() a middleware method Static files + default files + optional directory browsing, in one call.
UseDefaultFiles() a middleware method Serves index.html when a directory is requested. Must come before UseStaticFiles.
UseDirectoryBrowser() a middleware method Lists folder contents in the browser. A security risk — see traps.
StaticFileOptions a class Configures caching headers, extra folders, content types.
MIME type a content-type string image/png, text/css. Unknown extensions are not served by default.
FileExtensionContentTypeProvider a class Lets you register MIME types for unusual extensions.
PhysicalFileProvider a class Serves from a specific disk folder. Used to add folders beyond wwwroot.
MapStaticAssets() a method (.NET 9+) Newer alternative with build-time compression and fingerprinting.

The concept

Two folders, one of them public

Every ASP.NET Core app has two important directories, and confusing them is a security problem.

MyApp/                          ← CONTENT ROOT (not served)
├── appsettings.json            ← contains connection strings. NOT reachable.
├── Program.cs
├── MyApp.dll
└── wwwroot/                    ← WEB ROOT (publicly served)
    ├── css/site.css            ← anyone can download
    ├── js/app.js               ← anyone can download
    └── images/logo.png         ← anyone can download

Only wwwroot is served. A request for /appsettings.json returns 404, because that file is in the content root, not the web root.

That is a deliberate safety design. In classic ASP.NET the whole application folder was inside the site, so protecting files meant configuring IIS correctly. ASP.NET Core inverts the default: nothing is public unless you put it in wwwroot.

A picture: wwwroot is the shop window. Everything else is the stockroom. Anything you put in the window, anyone walking past can see. There is no lock on it.

Nothing is served unless you ask

Consistent with everything else in ASP.NET Core, static file serving is opt-in:

app.UseStaticFiles();     // without this line, wwwroot is not served at all

A brand-new Web API project does not include this, because an API has no CSS or images to serve. Add it only if you actually need it.


How it works

The simple version — enabling it

var app = builder.Build();

app.UseStaticFiles();     // serve everything in wwwroot

app.Run();

A file at wwwroot/css/site.css is now reachable at /css/site.css. The wwwroot part is not in the URL — it is the root.

Referencing it in HTML:

<link rel="stylesheet" href="~/css/site.css" />
<img src="~/images/logo.png" alt="Logo" />

The ~/ is a Razor convention meaning "from the web root", and it resolves correctly even when the app is hosted in a subfolder.

⚠️ Where to put it in the pipeline

Early — before authentication and routing.

app.UseHttpsRedirection();
app.UseStaticFiles();          // ← HERE
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Why it matters: middleware runs in order, and static files short-circuit the pipeline. When a request for /images/logo.png matches a file, that middleware returns it immediately and nothing below runs.

Put UseStaticFiles after authentication and every image request goes through JWT validation, a database lookup for claims, and routing — before serving a file that needed none of it. On a page with forty assets, that is forty pointless authentication cycles.

See 5.2.

⚠️ Static files are not protected

This is the security point of the note.

UseStaticFiles runs before authentication in the recommended order, which means files in wwwroot are served to anyone, with no authentication check at all.

wwwroot/
└── documents/
    └── salaries-2026.pdf     ← anyone who guesses the URL can download this

No login. No authorization policy. Just the URL.

If a file needs protection, it must not be in wwwroot. Serve it through a controller instead:

[Authorize(Policy = "HR")]
[HttpGet("documents/{id:guid}")]
public async Task<IActionResult> Download(Guid id, CancellationToken ct)
{
    var doc = await _docs.GetAsync(id, ct);
    if (doc is null) return NotFound();

    // Stored OUTSIDE wwwroot, so it is not directly reachable
    var path = Path.Combine(_env.ContentRootPath, "protected-docs", doc.FileName);

    return PhysicalFile(path, "application/pdf", doc.OriginalName);
}

Now the file lives outside the web root, and every download passes through authorization.

⚠️ And never build that path from user input — Path.Combine(root, userSuppliedName) with ../../appsettings.json is a path traversal attack. Look the filename up from your database using an ID, as above. See 17.11.

How it actually works — caching

By default static files are served with no caching headers, so browsers re-request them every time. For anything real you want caching:

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        // Cache for 7 days
        ctx.Context.Response.Headers.CacheControl = "public,max-age=604800";
    }
});

That creates the classic problem: how do users get a new version of site.css? They will keep the cached copy for a week.

The standard answer is cache busting — change the URL when the content changes:

<!-- Razor's asp-append-version adds a hash of the file contents -->
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<!-- renders as: /css/site.css?v=Kl_dqr9NVtnMdsM2MUg4qthUnWZm5T1fCEimBPWDNgM -->

The hash changes only when the file changes, so browsers cache aggressively and still pick up updates immediately.

In .NET 9+, MapStaticAssets() does this automatically, plus build-time compression:

app.MapStaticAssets();     // fingerprinting + gzip/brotli precompression

It is the better default for new apps.

The deeper detail — serving other folders and unknown types

A folder outside wwwroot:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(builder.Environment.ContentRootPath, "uploads")),
    RequestPath = "/files"        // reachable at /files/...
});

⚠️ Everything in that folder is now public too. The same rule applies — do not put anything sensitive there.

Unknown file extensions are not served. If the MIME type is unrecognised, the file is skipped and you get a 404 — which is confusing, because the file is clearly there:

var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".glb"] = "model/gltf-binary";
provider.Mappings[".webmanifest"] = "application/manifest+json";

app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider });

This is a deliberate safety default. Serving files of unknown type with a guessed content-type invites browsers to interpret them in unexpected ways. Register the types you genuinely need rather than enabling ServeUnknownFileTypes, which turns the protection off wholesale.

Should your app serve static files at all?

In production, often not. A CDN or reverse proxy does it better:

  • Served from an edge location near the user
  • Compression and caching handled for you
  • Your application threads stay free for actual requests

So the common production setup is: static assets on a CDN, API served by your app. Serving them from ASP.NET Core is fine for small apps and for development, and it is one of the first things to move when traffic grows.


Code

A complete configuration for an app that does serve its own assets:

var app = builder.Build();

app.UseHttpsRedirection();

if (app.Environment.IsDevelopment())
{
    // No caching locally, so changes appear immediately on refresh
    app.UseStaticFiles();
}
else
{
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            ctx.Context.Response.Headers.CacheControl = "public,max-age=604800";
        }
    });
}

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();

And the folder layout that keeps sensitive files out of reach:

MyApp/
├── appsettings.json              ← not served
├── protected-docs/               ← not served — reached only via controller
│   └── salaries-2026.pdf
└── wwwroot/                      ← PUBLIC
    ├── css/
    ├── js/
    └── images/

The rule to remember: if it should not be on the public internet, it does not go in wwwroot.


Interview questions

Q: How does ASP.NET Core serve static files?

Through the static files middleware, enabled with app.UseStaticFiles(). It serves the web root folder, which is wwwroot by default, and nothing else — so a request for appsettings.json returns 404 because that lives in the content root rather than the web root. Nothing is served unless you add the middleware, which is why a new Web API project has no static file support at all. The wwwroot segment does not appear in URLs; it is the root.

Q: Where should UseStaticFiles go in the pipeline, and why?

Early — before routing and authentication. Static file middleware short-circuits the pipeline when it matches a file, returning it immediately without running anything below. If you put it after authentication, every image and stylesheet request runs JWT validation and any claims lookup before serving a file that needed none of it. On a page with forty assets that is forty wasted authentication cycles per page load.

Q: Are static files protected by authorization?

No, and that is the important security point. Because the middleware runs before authentication, anything in wwwroot is downloadable by anyone who knows the URL, with no login and no policy check. So a file that needs protection must not live in wwwroot at all — you store it outside the web root and serve it through a controller action with an [Authorize] attribute, returning it with PhysicalFile. And you look the filename up by ID rather than building a path from user input, or you have created a path traversal vulnerability.

Q: How do you handle caching for static files?

By default they are served with no caching headers, so you set Cache-Control through OnPrepareResponse in StaticFileOptions. That creates the cache-invalidation problem, which you solve by changing the URL when the content changes — Razor's asp-append-version appends a content hash so browsers cache aggressively but pick up new versions immediately. In .NET 9 and later MapStaticAssets does the fingerprinting and build-time compression automatically. In production, though, static assets are often better served from a CDN entirely, which keeps your application threads free for real requests.


Traps ⚠️

  • Anything in wwwroot is public. No authentication, no authorization, ever.
  • UseStaticFiles placed after authentication wastes work on every asset request.
  • Nothing is served without UseStaticFiles(). New API projects do not include it.
  • Unknown file extensions return 404, which looks like the file is missing. Register the MIME type.
  • ServeUnknownFileTypes = true disables a safety check wholesale. Register specific types instead.
  • UseDirectoryBrowser lists your folder contents to anyone. Never enable it in production.
  • UseDefaultFiles must come before UseStaticFiles, or it has no effect.
  • Building a file path from user input is path traversal. Look it up by ID.
  • Content root and web root are different folders. Only one of them is public.


Sources