Configuring Default Page in ASP.NET Core

Configuring Default Page in ASP.NET Core

In this article, I will discuss how to configure the default page in the ASP.NET Core Web Application with examples. Please read our previous article, discussing How to Configure Static Files Middleware in ASP.NET Core Web Applications to serve static files such as Images, CSS, JavaScript, etc. At the end of this article, you will understand the Differences Between UseDirectoryBrowser, UseStaticFiles, UseFileServer, and UseDefaultFiles Middleware Components in the ASP.NET Core Application.

How to Configure Default Page in ASP.NET Core:

As we discuss everything from scratch, let’s create a new empty ASP.NET Core Web Application. To do so, open Visual Studio 2022 and click 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. 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 must 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, the following Additional Information window will open. Here, you need to select .NET 8 as the Framework, check the Configure for HTTPS and Do not use top-level statements check boxes, and finally, click the Create button, as shown in the image below.

Creating ASP.NET Core Web Application using Visual Studio

Once you click the Create Button, the Empty template will create the project. 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

By default, the ASP.NET Core Empty Project Template does not include the webroot folder, i.e., the wwwroot folder. So, let’s add the wwwroot folder to the project root directory. 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 shown below.

Adding wwwroot (webroot) Folder in ASP.NET Core

Adding HTML Page within the wwwroot Folder in ASP.NET Core Application:

Add one HTML page with the name index.html to the wwwroot folder. To do so, right-click on the wwwroot folder and then select add => new item, which will open the add new item window. From the new item window, search for HTML, select the HTML page, provide the HTML Page name as “index.html,” and then click the Add button as shown in the image below.

Adding HTML Page within the wwwroot Folder in ASP.NET Core Application

Once you add the HTML Page within the wwwroot folder, your project folder structure should look like the one below.

Configuring the Default Page in ASP.NET Core Web Application with Examples

Now, open the index.html file inside the wwwroot folder and copy and paste the following code.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1> This is Index HTML File</h1>
</body>
</html>
Modifying the Main Method of the Program Class:

To serve static files in ASP.NET Core Web Applications, we need to use the UseStaticFiles Middleware Component in the Request Processing Pipeline. So, let us modify the Main Method of the Program class, as shown below, to use the UseStaticFiles Middleware Component.

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();

            //Adding Another Terminal Middleware Component to the Request Processing Pipeline
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Request Handled and Response Generated");
            });

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

Now run the application and navigate to the URL: http://localhost:<portnumber>/index.html, and you will see the expected output coming from the static Index.html file, as shown in the image below.

Modifying the Main Method of the Program Class

Suppose you remove index.html from the URL or navigate to the base URL. In that case, the Terminal Middleware component will handle the request, which is registered using the Run Extension method. The Run Extension method will serve the default request, as shown in the image below.

Configuring the Default Page in ASP.NET Core Application

But what we want is when we navigate to the base URL, as shown above, the index.html page should serve the request. That is, we need to set the index.html page as our default page for the Root URL.

Setting the Default Page in ASP.NET Core Application:

Most 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 Page that will be displayed when a user visits the application’s root URL. For example, if you have a page with the name index.html and want that page to be your default page whenever any user visits your root URL, that page should be displayed.

To set the application’s default page to the index.html page inside the wwwroot folder, we need to add the UseDefaultFiles() middleware component to the Request Processing Pipeline. To do so, please modify the Main() Method of the Program class, as shown below, to use the UseDefaultFiles() middleware component.

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

            var app = builder.Build();

            //Setting the Default Files
            app.UseDefaultFiles();

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

            //Adding Another Middleware Component to the Request Processing Pipeline
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Request Handled and Response Generated");
            });

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

With the above changes in place, now run the application, and you should see the output as expected, as shown below. That index.html page serves as your default page.

Setting the Default Page in ASP.NET Core Application

Note: To serve the default file, you need to add the UseDefaultFiles() middleware before the UseStaticFiles() middleware. Remember that the UseDefaultFiles() middleware is just a URL rewriter and never serves the static files. The job of this middleware is to rewrite the incoming URL to the default file, which the Static Files Middleware will then serve.

How to Set Custom HTML Page as the Default Page?

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

  1. index.htm
  2. index.html
  3. default.htm
  4. default.html 

This is the default behavior. But if you want, then you can also change this default behavior. For example, let us add another HTML page into the project’s wwwroot folder named MyCustomPage1.html. Once you add the MyCustomPage1.html file, then the wwwroot folder contains two HTML files, as shown in the below image.

How to Set Custom HTML Page as the Default Page

Now, open the MyCustomPage1.html file and copy and paste the following code.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1> This is MyCustomPage1 HTML File</h1>
</body>
</html>
Setting MyCustomPage1.html as Default Page:

Now, we want the MyCustomPage1.html page to be our default page instead of the index.html page. To do this, you need to modify the Main() method of the Program class as follows. Here, we create an instance of the DefaultFilesOptions class, adding the default file name as MyCustomPage1.html, and then passing the DefaultFilesOptions instance to the UseDefaultFiles middleware component. The following code is self-explained, so please go through the comment lines for a better understanding.

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

            var app = builder.Build();

            //Specify the MyCustomPage1.html as the default page
            //First Create an Instance of DefaultFilesOptions
            DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();

            //Clear any DefaultFileNames if already there
            defaultFilesOptions.DefaultFileNames.Clear();

            //Add the default HTML Page to the DefaultFilesOptions Instance
            defaultFilesOptions.DefaultFileNames.Add("MyCustomPage1.html");

            //Setting the Default Files
            //Pass the DefaultFilesOptions Instance to the UseDefaultFiles Middleware Component
            app.UseDefaultFiles(defaultFilesOptions);

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

            //Adding Another Middleware Component to the Request Processing Pipeline
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Request Handled and Response Generated");
            });

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

Now run the application, and you will see the expected output from the MyCustomPage1.html file, as shown in the image below. If you still see the output from the index.html page, it may be due to cache, so try reloading it. If you are still not getting the data from the MyCustomPage1.html file, restart Visual Studio.

How to Configure the Default Page in the ASP.NET Core Web Application with Examples

What is the use of the UseFileServer() Middleware Component in ASP.NET Core?

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

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

            var app = builder.Build();

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

            //Adding Another Middleware Component to the Request Processing Pipeline
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Request Handled and Response Generated");
            });

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

Now run the application, and you will see the expected output, as shown in the image below.

What is the use of the UseFileServer() Middleware Component in ASP.NET Core?

Example to Understand UseDirectoryBrowser Middleware Component in ASP.NET Core Application:

One viewer asked in the comment section to give an example of the UseDirectoryBrowser Middleware Component in the ASP.NET Core Application. This middleware component enables directory browsing on the current path. Let us understand this with an example. Please modify the Main method of the Program class as follows. Here, I am using the UseDirectoryBrowser Middleware Component.

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

            var app = builder.Build();

            // Enable directory browsing on the current path
            app.UseDirectoryBrowser();

            app.UseStaticFiles();

            //Adding Another Middleware Component to the Request Processing Pipeline
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Request Handled and Response Generated");
            });

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

Now, run the application, and you will see the directory structure of the wwwroot folder, as shown in the below image.

Example to Understand UseDirectoryBrowser Middleware Component in ASP.NET Core Application

Differences Between UseDirectoryBrowser, UseStaticFiles, UseFileServer, and UseDefaultFiles in ASP.NET Core

In ASP.NET Core, several middleware components, such as UseDirectoryBrowser, UseStaticFiles, UseFileServer, and UseDefaultFiles, can serve files directly to the client. Understanding their differences is essential for correctly configuring how your application serves static content. 

UseStaticFiles:

It enables serving static files such as HTML, CSS, JavaScript, images, etc., directly to clients without any processing by the server. It serves files from the specified directory (wwwroot by default) based on the request URL path.
Middleware: app.UseStaticFiles();

UseDefaultFiles:

This Middleware allows specifying default files to be served when a directory is requested. When a URL maps to the base URL, it looks for a specific default file (like index.html, default.htm, etc.) in the wwwroot directory and serves it if found.
Middleware: app.UseDefaultFiles();

UseDirectoryBrowser:

This middleware enables directory browsing, allowing clients to see the contents of directories if an index file is not present. It also allows clients to view the contents of a directory if there’s no default file present (e.g., index.html). This is useful for debugging or exploring files on the server.
Middleware: app.UseDirectoryBrowser();

UseFileServer:

It combines several middleware functionalities into a single middleware. It includes static file serving, default file serving, and directory browsing. It enables static file serving (UseStaticFiles), default file serving (UseDefaultFiles), and directory browsing (UseDirectoryBrowser) under a single middleware setup. It’s a convenient way to enable all three functionalities together.
Middleware Class: app.UseFileServer();

Use Case:
  • Use UseStaticFiles and UseDefaultFiles for basic static file serving and default file handling scenarios.
  • Use UseFileServer when you need both static file serving and default file handling combined, along with directory browsing.
  • UseDirectoryBrowser is optional and should be used cautiously, typically for debugging or specific requirements where directory contents need to be visible.

In the next article, I will discuss the Developer Exception Page Middleware in ASP.NET Core Web Applications with Examples. In this article, I try to explain how to configure the default page in the ASP.NET Core Web Application with examples. I would like to get your feedback on this article. Please post your feedback, questions, or comments about this Configuring Default Page in the ASP.NET Core Web Application article.

5 thoughts on “Configuring Default Page in ASP.NET Core”

  1. blank

    Could you plz explain DirectoryBrowser middleware with a real-time example in a web application, why we use and when we should use…

Leave a Reply

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