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
