Advertisement
Beginner .NET, ASP.NET Core Middleware & Request Pipeline

How do you register built-in middleware for serving static files in an ASP.NET Core application?

Short answer

UseStaticFiles() middleware serves files from the wwwroot folder (by default) directly to clients without routing through MVC/controller logic, handling common concerns like content-type detection, caching headers, and range requests for things like CSS, JavaScript, and images…

Save .NET mock interview
Advertisement
AModel answer
UseStaticFiles() middleware serves files from the wwwroot folder (by default) directly to clients without routing through MVC/controller logic, handling common concerns like content-type detection, caching headers, and range requests for things like CSS, JavaScript, and images automatically.
var app = builder.Build();
app.UseStaticFiles();  // serves files from wwwroot by default

// Custom directory:
app.UseStaticFiles(new StaticFileOptions {
    FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "Assets")),
    RequestPath = "/assets"
});
Real-world example
A Blazor Server application relies on UseStaticFiles to serve its compiled CSS and JavaScript bundles directly from wwwroot, bypassing the routing and MVC pipeline entirely for better performance on static assets.
Likely follow-ups
  • How does UseStaticFiles interact with caching headers like Cache-Control?
  • What's the security risk of serving files outside the intended directory?
Related topics