Static Files Middleware in ASP.NET Core

Static Files Middleware in ASP.NET Core Application

In this article, I am going to discuss how to serve static files using Static Files Middleware in ASP.NET Core Application. Please read our previous article before proceeding to this article where we discussed the Request Processing Pipeline in ASP.NET Core Application. As part of this article, we are going to discuss the following pointers in details.

  1. Where do we need to store the static files in ASP.NET Core?
  2. What is wwwroot folder in ASP.NET Core?
  3. How to Configure Static Files Middleware in ASP.NET Core Web Application?
  4. What is the use of the UseFileServer() Middleware component?

One of the most important features almost all web applications should have the ability to serve the static files directly from the file system. The static files such as HTML, Images, CSS, and JavaScript are the important assets of an application and ASP.NET Core can serve these files directly to the clients. But the important point that you need to keep in mind by default the ASP.NET Core cannot serve these static files. Some configuration is required in order to enable the ASP.NET Core to serve these static files directly.

Where do we need to store the static files in ASP.NET Core?

In ASP.NET Core, the default directory or location for the static files is wwwroot (webroot) folder and moreover, this folder or directory should be present in the root project folder. By default, this is the only place where the ASP.NET Core application can serve the static files directly. But we can change this default behavior by using the UseWebRoot method that we will discuss in our upcoming articles. In this article, we are going with the default behavior.

Adding the wwwroot (webroot) folder:

Right-click on the project and then select add => new folder option and then provide the folder name as wwwroot.

Once you created the wwwroot folder, let’s add an HTML file within that folder. To do so, right-click on the wwwroot folder and then select add => new item which will open add new item window. From that window select the HTML template, provide a name such as “MyCustomPage1” and then click on the Add button as shown in the below image.

Static Files Middleware in ASP.NET Core

Once you click on the Add button, then it will add the HTML page within the wwwroot directory. Open the HTML file and then copy and paste the following code in it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>Serving Static Files in ASP.NET Core</h1>
</body>
</html>

Following is the directory structure of your application:

Static Files Middleware in ASP.NET Core Directory Structure

Following is the Configure() method of the Startup class.

Static Files Middleware in ASP.NET Core Configure Method

Now run the application and navigate to the following URL. The point that you need to remember is the port number may be different in your machine. 

http://localhost:59119/MyCustomPage1.html

So when you navigate to the above URL, you will not get the output as expected. Here you are getting the response from the middleware which is registered using the Run() extension method. The reason why we are not getting the output as expected because we don’t have any middleware which can serve the static files in the request processing pipeline.

Configuring Static Files Middleware:

The ASP.NET Core provides a middleware called UseStaticFiles() which can be used to serve the static files.

Let us Modify the Configure() method of the Startup class in order to add the UseStaticFiles() middleware to the request processing pipeline of the application as shown below. 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    //Adding Static Files Middleware to serve the static files
    app.UseStaticFiles();

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Request handled and response generated");
    });
}

Now run the application and navigate to the following URL and you will see the output as expected that is coming from the static HTML file.

http://localhost:59119/MyCustomPage1.html

Setting the Default Page:

Most of the web applications have a default page such as index.htm(l) or default.htm(l) as their startup page as it is easy to remember. This is the web page that is going to be displayed when a user visits the root URL of that application. For example, if you have a page with the name index.html and you want that page to be your default page so that whenever any user visits your root URL, then that page is going to be displayed.

Let’s add a new HTML File with the name index.html within the wwwroot folder of your project. Once you add the index.html file then copy and paste the following HTML code in it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>This is the Default Page</h1>
</body>
</html>

Now run the application and navigate to the root URL as shown below.

http://localhost:59119/

output.

Serving Static Files in ASP.NET Core

You are getting the response from the middleware which is registered using the Run() extension method. In order to serve the index.html page as the default page of your application, you need to add another middleware i.e. UseDefaultFiles() middleware into the request processing pipeline. So, modify the Configure() method of the Startup class as shown below to use the UseDefaultFiles() middleware which will set the default page for your application.

Setting Default Files in ASP.NET Core

Now run the application and you will see the output as expected.

Note: You need to add the UseDefaultFiles() middleware before the UseStaticFiles() middleware in order to serve the default file. The point that you need to remember is the UseDefaultFiles() middleware is just a URL rewriter and it never serves the static files. The job of this middleware is to simply rewrite the incoming URL to the default file which will then be served by the Static Files Middleware.

The UseDefaultFiles() middleware will search the wwwroot folder for the following files.

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

This is the default behavior. But if you want then you can also change this default behavior. For example, if you want MyCustomPage1.html page as the default page instead of the index.html then you need to modify the Configure() method of the Startup class as follows.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    //Specify the MyCustomPage1.html as the default page
    DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
    defaultFilesOptions.DefaultFileNames.Clear();
    defaultFilesOptions.DefaultFileNames.Add("MyCustomPage1.html");

    //Adding Default Files Middleware to set the default page 
    app.UseDefaultFiles();

    //Adding Static Files Middleware to serve the static files
    app.UseStaticFiles();

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Request handled and response generated");
    });
}

Now run the application and you will see the output as expected that is coming from the MyCustomPage1.html file. If you still see the output from the index.html page then it may be sue to cache so just try to reload the page. If still, you are not getting the data from the MyCustomPage1.html file then just restart the visual studio.

What is the use of the UseFileServer() Middleware component?

The UseFileServer() middleware components combines the functionality of UseStaticFiles, UseDefaultFiles and UseDirectoryBrowser middleware. We already discussed the UseStaticFiles and UseDefaultFiles middleware. The DirectoryBrowser middleware as the name says enables the directory browsing which allows the users to see the files which are stored in a specific directory. In our example, we can replace the UseStaticFiles() and UseDefaultFiles() middlewares with the UseFileServer() Middleware as shown below.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Use UseFileServer instead of UseDefaultFiles & UseStaticFiles
    FileServerOptions fileServerOptions = new FileServerOptions();
    fileServerOptions.DefaultFilesOptions.DefaultFileNames.Clear();
    fileServerOptions.DefaultFilesOptions.DefaultFileNames.Add("MyCustomPage1.html");
    app.UseFileServer(fileServerOptions);

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Request handled and response generated");
    });
}

Now run the application and you will see the output as expected.

In the next article, we are going to discuss the Developer Exception Page Middleware in detail. Here, in this article, I try to explain how to serve static files using Static Files Middleware in the ASP.NET Core application. I would like to have your feedback about this article. Please post your feedback, question, or comments about this article.

Leave a Reply

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