- Static files, such as HTML, CSS, images, and JavaScript, are assets that are served directly to the clients.
- Some configuration is required to enable to serving of these files.
- Static files are stored within your project's web root directory.
- The default directory is <content_root>/wwwroot, but it can be changed via the
UseWebRoot
method.
- The app's web host must be made aware of the content root directory.
- The
WebHost.CreateDefaultBuilder
method sets the content root to the current directory:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
- Static files are accessible via a path relative to the web root.
- The URI format to access a file in the images subfolder is http://<server_address>/images/<image_file_name>.
- The parameterless
UseStaticFiles
method overload marks the files in web root as servable.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
<img src="~/images/banner1.svg" alt="ASP.NET" class="img-responsive" />
Serve Files Outside of Web Root
- Consider a directory hierarchy in which the static files to be served reside outside of the web root:
- **wwwroot**
- **css**
- **images**
- **js**
- **MyStaticFiles**
- **images**
- *banner1.svg*
- A request can access the banner1.svg file by configuring the static file middleware as follows:
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles(); // For the wwwroot folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
RequestPath = "/StaticFiles" });
}
<img src="~/StaticFiles/images/banner1.svg" alt="ASP.NET" class="img-responsive" />
Set HTTP Response Headers