Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 52 ยท Middleware and the Request Pipeline

Static Files, Default Documents and CORS

Serve static files in ASP.NET Core with UseStaticFiles, file providers, content types and cache headers, then configure CORS policies and understand preflight requests.

Two jobs show up in almost every web project and both are handled by middleware. The first is serving files that never change per request: HTML pages, CSS, JavaScript bundles, images, fonts. The second is deciding whether a web page loaded from another origin is allowed to call your API from the browser. ASP.NET Core calls these static files and CORS (Cross-Origin Resource Sharing).

This lesson covers both. You will see how UseStaticFiles maps a folder to URLs, how default documents like index.html work, how content types and caching headers are decided and how to configure CORS policies and read a preflight exchange. Static files are served from a real folder on disk, so our examples create a temporary folder first. Make sure you have read the middleware pipeline, because the order in which you register these components matters.

Static files: from folder to URLs

A new web project has a folder called wwwroot. It is the web root. Anything inside is public, and nothing outside is. UseStaticFiles() with no arguments serves files from the web root, with the folder name left out of the URL: wwwroot/css/site.css is reachable at /css/site.css.

flowchart LR
    R["GET /css/site.css"] --> SF["UseStaticFiles"]
    SF -->|"file exists"| F["200 + file bytes"]
    SF -->|"no file"| N["next middleware<br/>(routing, endpoints)"]
    N --> E["404 or an endpoint"]

The static file middleware answers only if a matching file exists; otherwise the request continues down the pipeline.

That second branch matters: static files do not return 404 themselves. They simply pass the request on. Because they are cheap and answer quickly, you normally put them early in the pipeline, before authentication, logging of every request or anything else you do not need for an image.

The web root is public. Never put configuration files, source code or user uploads that should be private inside wwwroot. If a file needs a permission check, serve it from an endpoint instead of from the static file middleware.

File providers

The middleware does not read the disk directly. It talks to an IFileProvider, an abstraction over "a place with files". The default is a PhysicalFileProvider on the web root. You can pass your own to serve a second folder under a URL prefix:

C#
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "assets")),
    RequestPath = "/assets"
});

Now assets/logo.svg on disk is served at /assets/logo.svg. Other providers exist too: EmbeddedFileProvider (files compiled into an assembly) and CompositeFileProvider (several providers combined).

Default documents

When a visitor opens / or /docs/, they expect index.html to show up. That is the job of UseDefaultFiles(). It does not serve anything itself. It rewrites the request path to /index.html (or index.htm, default.html, default.htm) if such a file exists, and then UseStaticFiles() serves it. So UseDefaultFiles must come before UseStaticFiles. UseFileServer() combines both calls, and can also enable directory browsing, which you should leave off on public sites.

Content types and unknown extensions

Browsers rely on the Content-Type header to decide what to do with a response. The middleware picks it from the file extension using a FileExtensionContentTypeProvider, which already knows several hundred extensions (.html, .css, .js, .json, .svg, .woff2, .wasm, ...).

For safety, files whose extension is not in the table are not served at all: the request falls through and ends in a 404. You have two ways to deal with that:

  • Add the mapping: provider.Mappings[".dat"] = "application/octet-stream";
  • Set ServeUnknownFileTypes = true and a DefaultContentType. This works but can expose files you did not mean to publish, so the mapping is the better habit.

Caching headers

Static files are the best candidates for caching. The middleware already sends Last-Modified and a strong-ish ETag for each file, so browsers can ask "has it changed?" with If-None-Match and receive a body-less 304 Not Modified when it has not. To go further, tell browsers they do not need to ask at all for a while by adding Cache-Control in the OnPrepareResponse callback.

A practical rule: fingerprinted files (app.3f9c2a.js, where the name changes whenever the content does) can be cached for a year with immutable; files with stable names (index.html) should be revalidated, so they use no-cache or a short max-age.

The example below creates a temporary folder with three files, wires up default documents, an extra content type mapping and cache headers, and then examines the responses.

C# Serving files from a folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the output line by line:

  • / was rewritten to /index.html by UseDefaultFiles and served as text/html.
  • site.css carries the long-lived cache header; index.html must revalidate.
  • table.dat is served because we added the mapping; notes.xyz is not served (the middleware passed it on and nothing else matched, so it is a 404).
  • /api/ping shows the pipeline order at work: no file named api/ping, so the request reaches the endpoint.
  • Sending the ETag back as If-None-Match produces 304 Not Modified with no body.

In .NET 9 and later, the new MapStaticAssets() endpoint (used by the newer web templates) replaces UseStaticFiles for the web root: it fingerprints files at build time and serves them with precomputed compressed variants and strong cache headers. The ideas above (web root, content types, validators, caching) are the same; UseStaticFiles is still the right tool for extra folders and simple apps.

What is CORS, and why does it exist?

Browsers enforce the same-origin policy: a script loaded from https://shop.example may not read responses from https://api.example unless the API says that is fine. An origin is the combination of scheme, host and port; changing any one of them makes it a different origin (http://localhost:3000 and http://localhost:5000 are different origins).

CORS is the protocol that lets a server opt in. The server answers with headers such as Access-Control-Allow-Origin, and the browser decides whether the page's script may see the response. Two details are frequently misunderstood:

  • CORS is enforced by browsers, not by servers. curl, Postman and other servers ignore it. It protects users' browsers, not your API. It is not authentication.
  • The request still reaches your server. For simple requests the server runs your endpoint; CORS only controls whether the browser shows the result to the script.

Simple requests and preflight

Some requests are "simple" (a GET or form-style POST with common headers). The browser sends them directly with an Origin header and checks the answer. Anything else, such as PUT, DELETE, JSON POST with Content-Type: application/json or custom headers like Authorization, triggers a preflight: before the real request, the browser sends an OPTIONS request that asks permission.

sequenceDiagram
    participant B as Browser (shop.example)
    participant S as API (api.example)
    B->>S: OPTIONS /orders<br/>Origin: https://shop.example<br/>Access-Control-Request-Method: PUT
    S-->>B: 204 + Access-Control-Allow-Origin<br/>Allow-Methods, Allow-Headers, Max-Age
    B->>S: PUT /orders (the real request)
    S-->>B: 200 + Access-Control-Allow-Origin

A preflight asks permission first; only if the answer allows it does the browser send the real request.

CORS in ASP.NET Core

Register policies with AddCors, then enable them with UseCors. A policy is built from the same vocabulary as the headers:

Builder method Header it controls
WithOrigins("https://shop.example") Access-Control-Allow-Origin
AllowAnyOrigin() * (cannot be combined with credentials)
WithMethods("GET", "PUT") / AllowAnyMethod() Access-Control-Allow-Methods
WithHeaders("Content-Type") / AllowAnyHeader() Access-Control-Allow-Headers
WithExposedHeaders("X-Total-Count") Access-Control-Expose-Headers
AllowCredentials() Access-Control-Allow-Credentials
SetPreflightMaxAge(...) Access-Control-Max-Age

Place UseCors() after routing and before authentication and authorization, so that preflight requests (which carry no credentials) get an answer before an authentication check can reject them. In minimal APIs you can apply a named policy to a single endpoint with .RequireCors("name").

AllowAnyOrigin() is fine for a truly public, read-only API. Combine it with cookies or other credentials and the browser refuses it, which is intentional. For credentialed requests, list the exact origins. Never reflect an arbitrary Origin header back without checking it against a list.

The next example sets up one strict policy and inspects what the server says to three different callers: an allowed origin, a disallowed origin and a preflight. We set the Origin header by hand because there is no browser here.

C# CORS headers and a preflight

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The "stranger" case is the one to remember: the server still answered 200 and ran the endpoint. It simply withheld the Access-Control-Allow-Origin header, which makes a real browser hide the response from the script. That is why CORS can never replace authorization.

The last call shows a subtler point. The server answered the DELETE preflight with 204 and the same list, GET,PUT. It does not say "no"; it states what the policy allows, and the browser compares that list with the method it wanted to use and refuses to send the real DELETE. The server never has to reject anything itself.

Putting it together in Program.cs

A typical ordering for a site that serves a front end and an API looks like this (read-only, because it needs a real project):

C#
var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler();
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();     // cheap, answer images and CSS early

app.UseRouting();
app.UseCors();            // after routing, before auth
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/api/hello", () => "hi").RequireCors("frontend");
app.Run();

Notice how static files come before routing and authentication: a request for a stylesheet should not pay for a login check. Authentication itself arrives in authentication concepts.

Common mistakes

  • Putting UseDefaultFiles after UseStaticFiles. The rewrite happens too late and / returns 404.
  • Serving files from the wrong root. In a real project the web root is wwwroot inside the content root. Files elsewhere are invisible unless you add a provider.
  • Enabling directory browsing in production, which lists every file in a folder.
  • Treating CORS as security. It only controls what browsers show to scripts. Always authorize on the server.
  • Forgetting that preflight needs an answer without credentials. Put UseCors before authentication.
  • Mixing AllowAnyOrigin with AllowCredentials. ASP.NET Core rejects that combination at runtime; use explicit origins.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request arrives for /logo.png and no such file exists in the web root. What does UseStaticFiles do?

    The static file middleware only answers when it finds a matching file. Otherwise the request continues, and a later endpoint or the default 404 handles it.
  2. 2. What is the correct ordering of UseDefaultFiles and UseStaticFiles?

    UseDefaultFiles rewrites '/' to '/index.html' and UseStaticFiles serves it, so the rewrite must happen first.
  3. 3. Why does a file named notes.xyz return 404 by default?

    Files with unknown extensions are not served unless you add a mapping to the content type provider or enable ServeUnknownFileTypes.
  4. 4. Who enforces CORS?

    The server only sends headers. Browsers enforce them for page scripts; curl and other servers ignore CORS entirely, so it is not an access-control mechanism.
  5. 5. When does a browser send a preflight OPTIONS request?

    Non-simple cross-origin requests (other methods, custom headers, JSON content type) are preceded by a permission check using OPTIONS.

Summary

  • UseStaticFiles serves the web root (wwwroot) and passes on requests that match no file; register it early.
  • UseDefaultFiles rewrites / to index.html and must come before UseStaticFiles; UseFileServer combines them.
  • An IFileProvider decides where files come from; add a second provider with a RequestPath for extra folders.
  • Unknown extensions are not served unless you add a content type mapping; use OnPrepareResponse for Cache-Control, and rely on ETag with 304 for revalidation.
  • CORS is a browser rule: servers send Access-Control-* headers, and browsers decide whether scripts may read the response.
  • Define policies with AddCors, enable with UseCors after routing and before authentication, and never treat CORS as authorization.

Next: Dependency Injection in ASP.NET Core