Static Files Middleware in ASP.NET Core

Static Files Middleware in ASP.NET Core (.NET 6) Application

In this article, I will discuss How to Serve Static Files using Static Files Middleware in ASP.NET Core (.NET 6) Web Application with Examples. Please read our previous article before proceeding to this article, where we discussed the wwwroot folder in the ASP.NET Core Application. As part of this article, we will discuss the following pointers in detail.

  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 do you configure static files middleware in the ASP.NET Core Web Application?
  4. How to use your own Webroot folder?

One of the most important features of almost all web applications should be the ability to serve static files directly from the file system. 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 you need to remember is that by default, the ASP.NET Core cannot serve these static files. Some configuration is required to enable the ASP.NET Core to serve these static files directly.

Static Files Middleware

Static Files Middleware in ASP.NET Core is a feature used to serve static files such as HTML, CSS, JavaScript, and image files. It’s a crucial part of web development since these files are typically the building blocks of web applications. These files are not processed by server code; they are sent to the client as-is. Examples include .html, .css, .js, and image files.

Where do we need to store the Static Files in ASP.NET Core (.NET 6)?

In the ASP.NET Core Application, the default directory or location for the static files is the wwwroot (webroot) folder; moreover, this folder or directory should be present in the project root 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 WebApplicationOptions Instance and WebRootPath property.

Example to understand Static Files in .NET 6 Application:

Create a new ASP.NET core application using the ASP.NET Core Empty template. To create a new Empty ASP.NET Core Web Application, open Visual Studio 2022 and click on the Create a new project tab as shown in the image below.

Understanding Program.cs Class File in ASP.NET Core

Once you click on the Create a new project tab, it will open the Create a new project window. You need to select the ASP.NET Core Empty project template from this window and click the Next button, as shown in the image below.

What is a Host in ASP.NET Core?

Once you click on the Next button, it will open the Configure Your New Project window. Here, you need to provide the necessary information to create a new project. First, give an appropriate name for your project (FirstCoreWebApplication), set the location where you want to create this project, and the solution name for the ASP.NET Core Web application. And finally, click on the Create button, as shown in the image below.

What is Program Class?

Once you click on the Next button, it will open the Additional Information window. Here, you need to select .NET 6.0 as the Framework. You also need to check the Configure for HTTPS and Do not use top-level statements check boxes, and finally, click on the Create button as shown in the image below.

ASP.NET Core Main Method in .NET 6

That’s it. Once you click on the Create Button, the project will be created with the Empty template. With the Empty project template by default, you will not find the wwwroot folder. The project structure of the ASP.NET Core Web Application with the Empty Project template is shown below.

ASP.NET Core Main Method in .NET 6

As you can see in the above image, there is no such folder called wwwroot in our application. If you create the Project using a Web API or MVC (Model-View-Controller) Project Template, then by default, the wwwroot folder will be created by Visual Studio.

Adding the wwwroot (webroot) Folder:

Let us first create the wwwroot Project Folder. To do so, right-click on the project, select the add => new folder option from the context menu, and then provide the folder name as wwwroot. Once you create the wwwroot folder, your project structure should be as shown below.

Adding wwwroot (webroot) Folder in ASP.NET Core

Once you have created the wwwroot folder, let’s add an Image file within that folder. Please download and paste the following image into the wwwroot folder and modify the image name as MyImage.png.

Dot Net Tutorials Logo

Once you save the above image, your wwwroot directory looks as shown below.

Adding Image to the wwwroot (webroot) Folder

Now run the application and navigate to the following URL. You need to remember that you need to replace the port number on which your application is running. 

http://localhost:<portnumber>/MyImage.png

When you navigate to the above URL, you will not get the output as expected; rather, you will get the following output.

ASP.NET Core Static Files Middleware

We are not getting the output as expected because we don’t have any middleware that can serve the static files in the request processing pipeline.

How do you configure the static files middleware in the ASP.NET Core Application?

To handle the static resources, we need to configure a middleware called UseStaticFiles() into the application request processing pipeline of an ASP.NET Core Application. The UseStaticFiles() middleware is an inbuilt middleware component provided by the ASP.NET Core Framework to handle the static files in an ASP.NET Core Web Application.

Let us Modify the Main() Method of the Program class as shown below to add the UseStaticFiles() Middleware Component to the Request Processing Pipeline of the application. 

namespace FirstCoreWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            var app = builder.Build();

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

            app.MapGet("/", () => "Hello World!");

            //This will Run the Application
            app.Run();
        }
    }
}

With the above changes in place, now run the application and navigate to the URL: http://localhost:<portnumber>/MyImage.png, and you will see the output as expected, as shown in the below image.

How to Configuring the Static Files Middleware in ASP.NET Core Application

Note: If you are working with Earlier Versions of .NET Core Framework like ASP.NET Core 3 and .NET 5, then you need to configure the UseStaticFiles() Middleware component within the Configure() method of the Startup class.

How do you create your own Webroot Folder in ASP.NET Core (.NET 6)?

Let’s say we don’t want wwwroot as our webroot folder; instead, we want MyWebRoot as the webroot folder for our application. First, modify the wwwroot folder as MyWebRoot, and once you modify it, your project structure should be as shown below.

How to Create your own Webroot Folder in ASP.NET Core

At this point, if you run the application, then you will not get the output as shown in the below image.

ASP.NET Core Static Files Middleware

This is because, by default, the static files middleware will look for a folder named wwwroot that is not present in our application. But we don’t want wwwroot. We want the Static files middleware to look at the MyWebRoot folder to the server, the static files such as CSS, Images, JS, etc. To do so, we need to tell the ASP.NET Core Framework to use MyWebRoot as the web root path. To do so, we need to set the WebRootPath property to MyWebRoot while creating the WebApplicationBuilder instance. So, for a better understanding, please modify the Main method of the Program class as shown below to configure the MyWebRoot folder as the webroot folder for our application.

namespace FirstCoreWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //var builder = WebApplication.CreateBuilder(args);

            //Setting Custom Web Root Folder
            WebApplicationBuilder builder = WebApplication.CreateBuilder(new WebApplicationOptions
            {
                WebRootPath = "MyWebRoot"
            });

            var app = builder.Build();

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

            app.MapGet("/", () => "Hello World!");

            //This will Run the Application
            app.Run();
        }
    }
}

With the above changes in place, run the application, and you should get the output as expected, as shown in the image below.

How to Configuring the Static Files Middleware in ASP.NET Core Application

Note: If you are working with earlier versions of .NET Core, such as ASP.NET Core 3.1, then to configure the custom web root, you need to call the UseWebRoot method by passing MyWebRoot as a parameter in the CreateHostBuilder method, which is available in the Program class as shown below.

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>().UseWebRoot("MyRoot");
            });
}

In the next article, we will discuss the Configuring Default Page in ASP.NET Core Application with Examples. In this article, I explain How to Serve Static Files using the Static Files Middleware Component in ASP.NET Core Web Application with Examples. I would like to have your feedback about this article. Please post your feedback, questions, or comments about this Static Files Middleware Component in the ASP.NET Core Web Application article.

4 thoughts on “Static Files Middleware in ASP.NET Core”

  1. It’s missing parameter defaultFilesOptions in app.UseDefaultFiles(), if you want to display MyCustomPage1.html instead of default index.html…

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

Leave a Reply

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