liveBook · Manning

Staticfilemiddleware

As explained in ASP.NET Core in Action, 3e

StaticFileMiddleware is the ASP.NET Core middleware component that serves existing files from a configured file directory in response to matching requests.

StaticFileMiddleware serves existing static files from the application's wwwroot folder. It commonly delivers images, JavaScript, CSS, and static HTML directly to browsers. section 4.2.2 section 13.1.1

Add static-file handling

A minimal application needs only the middleware registration: `WebApplicationBuilder builder = WebApplication.CreateBuilder(args); WebApplication app = builder.Build(); app.UseStaticFiles(); app.Run();` Place `moon.jpg` in wwwroot and request `/moon.jpg` to receive the image. section 4.2.2

Request handling follows a simple rule:

  • Checks whether the requested file exists in wwwroot. section 4.2.2
  • Returns the file when it exists, allowing the middleware to handle the request. section 4.2.2
  • Passes an unknown file request onward; an unhandled request ultimately produces a 404 response. section 4.2.2 section 4.4
Listing 4.2 Program.cs for a static-file middleware pipeline
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
 
app.UseStaticFiles();    #1
 
app.Run();
#1 Adds the StaticFileMiddleware to the pipeline

Use the runnable Program.cs listing to see the single middleware call that adds StaticFileMiddleware to the pipeline. section 4.2.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains registration, file lookup, response handling, and 404 behavior, but does not detail custom file-provider configuration.
Examples
Uses moon.jpg as a successful request and missing.jpg as a missing-file request that produces a 404.
What it assumes
Assumes basic ASP.NET Core application structure and explains wwwroot and middleware registration directly.
What you can do after
Operate/configure static-file serving by adding UseStaticFiles and placing browser-accessible assets under wwwroot.
How it connects
Connects static files with wwwroot, middleware pipelines, HTTP 404 responses, Razor Pages, and minimal APIs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.