liveBook · Manning

Static file

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

A static asset is a web resource such as an image, stylesheet, or script file that is served without being dynamically generated for each request.

A static file is a web resource such as an image, JavaScript file, or CSS stylesheet served directly from disk rather than generated for each request. In ASP.NET Core, static files normally live in the wwwroot folder and are returned by static-file middleware. section 4.2.2

ASP.NET Core handles static-file requests in a small, focused pipeline:

  • UseStaticFiles adds StaticFileMiddleware to the application pipeline. section 4.2.2
  • The middleware checks wwwroot for the requested path and returns the file when it exists. section 4.2.2
  • Files outside wwwroot are not served by default, helping prevent unintended access to other application folders. section 4.2.2
  • A missing file produces an HTTP 404 response instead of a file response. section 4.2.2

Serving an image

Place moon.jpg in wwwroot and configure the application with app.UseStaticFiles();. A request for /moon.jpg is handled by StaticFileMiddleware and returns the image. A request for /missing.jpg returns 404. section 4.2.2

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

The minimal Program.cs listing shows that a static-file application needs only WebApplication construction, UseStaticFiles, and app.Run. section 4.2.2

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

How deep it goes
Explains middleware configuration, wwwroot lookup, successful responses, and 404 handling without deeper file-serving customization.
Examples
Uses wwwroot, moon.jpg, missing.jpg, UseStaticFiles, and a minimal Program.cs pipeline.
What it assumes
Starts from a minimal ASP.NET Core application and requires no additional services to configure static-file middleware.
What you can do after
Apply it via ASP.NET Core's UseStaticFiles method to serve files from wwwroot and recognize missing-file 404 responses.
How it connects
Connects static files to middleware pipelines, wwwroot, HTTP 404 responses, and dynamic web applications.

Also explained in

Compare how 6 books explain static file →

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.