Static Files Middleware in ASP.NET Core

Introduction

In this article, we will discuss Static Files Middleware in ASP.NET Core and how it serves static files such as HTML, Images, JavaScript and CSS files. by default, an ASP.NET Core application will not be able to serve static files to be able to serve static files. our application should meet two requirements first all the static files must be present in the wwwroot folder.

Please, read our previous article before proceeding to this article where we learn Middleware Components And Request Pipeline in ASP.NET Core.

It is called the content root folder and it must be inside the root project folder. in our case, the root project folder and a web root folder wwwroot. the truth is within that project root folder and all the static files that you want to be able to serve from the asp.net core application.

Serve static files

Serve static files in asp.net core

The Static files are stored inside the project’s web root directory. So, its default directory is {content root}/wwwroot, but it can change via the UseWebRoot method.

The app’s web host must make aware of the application content root directory.

So, we use WebHost.CreateDefaultBuilder method inside the program.cs file and it sets the content root to the current directory, see the following example:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args) 
            .UseStartup<Startup>();
}

The Static files are accessible through a relative path to the webroot. For example, the Web Application project template and other static files contain several folders within the wwwroot folder:

Static files in asp.net core

Serve files inside of webroot

It Invokes the UseStaticFiles method within Startup.Configure:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); 
}

The parameterless UseStaticFiles extension method overload marks the files in webroot as servable. The following markup references wwwroot/images/banner1.svg:

<img src="~/images/banner1.svg" alt="ASP.NET" class="img-responsive" />

So, in the preceding code, the tilde character ~/ points to the webroot.

Serve files outside of webroot

Consider a directory hierarchy in which the static files to serves to reside outside of the webroot:

wwwroot directory in asp.net core

the request can access the banner1.svg file by configuring the Static File Middleware extension method 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"
    }); 
}

Serve a default document

by default, the StaticFiles middleware will only serve static files that are present in this wwwroot. it’s also possible to serve static files that are outside of the webroot folder.

most of the web applications also have a default document and it is that default document that is displayed. when we navigate to the root URL of our application.

for example, when we navigate to localhost without any other URL segments. we want to serve the default document but at the moment we see the response produced by the middleware that is registered using a run method. first, let’s add a default page for our application by default the name of the default page for our application should be one of the following default

default.htm
default.html
index.htm
index.html

So, we can define the setting as a default home page that provides visitors a logical starting point when visiting your site. To serve a default page without the user qualifying the URI and call the UseDefaultFiles method from Startup.Configure:

public void Configure(IApplicationBuilder app)
{
    app.UseDefaultFiles(); 
    app.UseStaticFiles();
}

In the beginning, the first file found from the list serves as though the request were the qualified URI. So the browser URL continues to reflect the URI requested.

The below code changes the default file name to mydefault.html:

public void Configure(IApplicationBuilder app)
{
    // Serve my app-specific default file if present.
    DefaultFilesOptions options = new DefaultFilesOptions();
    options.DefaultFileNames.Clear();
    options.DefaultFileNames.Add("mydefault.html");
    app.UseDefaultFiles(options);
    app.UseStaticFiles();
}

UseFileServer

The UseFileServer combines the functionality of UseDefaultFiles, UseStaticFiles and optionally UseDirectoryBrowser.

The below code enables the serving of static files and the default file. Directory browsing is not enabled.

app.UseFileServer();

The below, code builds using the parameterless overload by enabling directory browsing:

app.UseFileServer(enableDirectoryBrowsing: true);

Consider the following directory hierarchy:

useWebserver in asp.net core

The following code enables default files, static files and directory browsing of MyStaticFiles:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
        RequestPath = "/StaticFiles",
        EnableDirectoryBrowsing = true
    }); 
}

Thank you for reading this article, I hope you will understand the Static Files Middleware in ASP.NET Core. We’ll get into more details about this when we’ll learn How to use Dependency Injection in ASP.NET Core in the next article.

Leave a Reply

Your email address will not be published. Required fields are marked *