Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.
Serve files in web root
Static files are stored within the project's web root directory, the default directory is {content root}/wwwroot. For more information, see Content root and Web root.
The CreateBuilder method sets the content root to the current directory, the default web app templates call the UseStaticFiles method in Program.cs, which enables static files to be served:
var builder = WebApplication.CreateBuilder(args);
...
var app = builder.Build();
...
app.UseStaticFiles();
...
app.Run();
For example, create a new folder "image" under wwwroot and add wwwroot/image/MyImage.jpg file. The URI format to access MyImage.jpg file in the image folder is https://<hostname>/image/<image_file_name>.
Please note there is NO "wwwroot" in the URL, so markup references should be:
<img src="~/image/MyImage.jpg" alt="My image" />
Serve files outside of web root
/wwwroot
--/css
--/js
/upload
--/image
--/MyImage.jpg
A request can access the MyImage.jpg file by configuring the Static File Middleware as follows:
using Microsoft.Extensions.FileProviders;
var builder = WebApplication.CreateBuilder(args);
...
var app = builder.Build();
...
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, "upload")),
RequestPath = "/upload"
});
...
app.Run();
A request to https://<hostname>/upload/image/MyImage.jpg serves the MyImage.jpg file. The markup references should be:
<img src="~/upload/image/MyImage.jpg" alt="My image" />
To serve files from multiple locations:
app.UseStaticFiles(); // serve files from wwwroot
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, "upload")),
RequestPath = "/upload"
}); // serve files from upload folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, "document")),
RequestPath = "/document"
}); // serve files from document folder
Article ID: 2220, Created: May 12, 2022 at 1:15 AM, Modified: May 12, 2022 at 2:25 AM