Overview
Static files are stored in the web root directory CONTENT_ROOT/wwwroot. Change with UseWebRoot. Serve with UseStaticFiles.
serve static files in the web root
Static files are accessible via a path relative to the web root. If you create wwwroot/images/ and add SomeImage.jpg,
- access via URL at
https://hostname/images/SomeImage.jpg - and via markup:
<img src="~/images/MyImage.jpg" class="img" alt="My image" />
serve static files outside of the web root
Use UseStaticFiles and pass StaticFileOptions:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "SomeDirectory")), // The new static files directory
RequestPath = "/StaticFiles" // The static files directory, SomeDirectory, is exposed via the /StaticFiles URI segment.
});
Static files can be reached
- via URL at
https://hostname/StaticFiles/… - via markup:
<img src="~/StaticFiles/images/red-rose.jpg" class="img" alt="A red rose" />
set http response headers
Use StaticFileOptions:
// Make static files publicly available in the local cache for one week via the Cache-Control header:
var cacheMaxAgeOneWeek = (60 * 60 * 24 * 7).ToString();
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cacheMaxAgeOneWeek}");
}
});