ASP.NET Core MVC Beginner

Serving static files

CSS, JavaScript, images and fonts are static files: the server sends them as they are. This lesson explains the wwwroot folder, how static files are served and cached, and how to make sure browsers pick up new versions.

How a static file is served
  1. StartBrowser asks for a fileGET /css/site.css
  2. Step 2Static files middleware checksDoes wwwroot/css/site.css exist?
  3. Step 3FoundReturn the file with caching headers; the pipeline stops here
  4. EndNot foundPass the request on to routing and controllers

The idea in plain words

Files in the wwwroot folder are served directly by the static files middleware, without going through controllers. A request for /images/logo.png returns wwwroot/images/logo.png. In Razor, ~/ means the web root, so ~/css/site.css always points to the right place.

Newer project templates use MapStaticAssets, which adds build-time compression and fingerprinted file names for strong caching. Older apps use UseStaticFiles. Either way, add asp-append-version="true" (or rely on MapStaticAssets) so browsers download a file again when it changes.

Example

C#
// Program.cs (.NET 9 and later templates)
app.MapStaticAssets();

// Older style
app.UseStaticFiles();

// Serve files from another folder under a URL prefix
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(builder.Environment.ContentRootPath, "Docs")),
    RequestPath = "/docs"
});

In views

Razor
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<script src="~/js/site.js" asp-append-version="true"></script>
<img src="~/images/logo.png" alt="Shop logo" />

Common mistakes

  • Putting private files in wwwroot. Everything there is public; there is no authorization check by default.
  • Placing the static files middleware after authentication so every image requires sign-in (or before it when files really should be protected).
  • Changing CSS and wondering why users still see the old design; use versioned URLs.
  • Hard-coding absolute paths instead of using ~/.

Interview question

Are static files in ASP.NET Core protected by authorization?

Not by default. The static files middleware serves anything under wwwroot without checking authorization, and it usually runs before authentication. To protect files, store them outside wwwroot and serve them from an action that has [Authorize] and returns File(...), or place the static files middleware after UseAuthorization with an authorization fallback policy.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.