Configuring Default Page in ASP.NET Core

Configuring Default Page in ASP.NET Core

In this article, I will discuss Configuring the Default Page in 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 are going to discuss everything from scratch, let us create a new ASP.NET Core Empty Application. 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 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, 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. 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

With the ASP.NET Core Empty Project Template by default, the webroot folder, i.e., wwwroot folder, will not be available. So, let us add the wwwroot folder to the project root directory. 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

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

Let us add one HTML Page with the name index.html within 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 on 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 as shown below.

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

Now, open the index.html file, which is present inside the wwwroot folder, and then copy and paste the following code into it.

<!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 the 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 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 terminating middleware will handle the request registered using the Run method. The Run 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, we want our index.html page to serve the request. We need to set the index.html page as our default page.

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 Web Page that will 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 want that page to be your default page whenever any user visits your root URL, that page should be displayed.

To serve the index.html page, which is present inside the wwwroot folder as the default page of your application, you need to add another middleware component, i.e., UseDefaultFiles() middleware, into the Request Processing Pipeline. So, modify the Main() Method of the Program class as shown below to use the UseDefaultFiles() middleware component to set your application’s default page.

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. You need to remember that the UseDefaultFiles() middleware is just a URL rewriter, and it 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 coming 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 output as expected, as shown in the below image.

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. I am updating the content from ASP.NET Core 3,1 to .NET 6, so I am adding the example here. 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, there are several middleware components that you can use to serve files directly to the client, such as UseDirectoryBrowser, UseStaticFiles, UseFileServer, and UseDefaultFiles. Understanding their differences is essential for correctly configuring how your application serves static content. Let’s delve into each one:

UseDirectoryBrowser
  • Purpose: This middleware allows you to browse the directory structure of your application on the web. It’s primarily used for development purposes as it exposes the directory structure to the client.
  • Behavior: When you navigate to a URL that maps to a directory on the server, it presents a view of the directory’s contents. It lists files and directories and allows you to navigate through them.
  • Security Consideration: It should not be used in a production environment unless you have a specific need to expose the directory structure to the end-user, as it can reveal sensitive information about the server’s file system.
UseStaticFiles
  • Purpose: This is the most common middleware for serving static files (like images, JavaScript, CSS files) in ASP.NET Core applications.
  • Behavior: It maps a request path to a physical file system path and serves the file located at that path. It does not list directory contents; it only serves individual files.
UseDefaultFiles
  • Purpose: This middleware configures the default file to be served to a directory when a request is made. Commonly, it’s used to serve index.html or default.html when the root of the site is accessed.
  • Behavior: It doesn’t serve the file itself but rather rewrites the URL to the default file, which UseStaticFiles then picks up.
  • It must be called before UseStaticFiles as it only rewrites the URL, relying on UseStaticFiles actually to serve the file.
UseFileServer
  • Purpose: UseFileServer is essentially a convenience method that combines the functionality of UseStaticFiles, UseDefaultFiles, and, optionally, UseDirectoryBrowser.
  • Behavior: It enables the serving of static files, and it can also enable directory browsing and default file serving (like serving index.html when the root URL is accessed).
In summary:
  • UseDirectoryBrowser is for browsing directories (mostly for development).
  • UseStaticFiles serves individual static files.
  • UseDefaultFiles rewrites URL requests to serve default files, used in conjunction with UseStaticFiles.
  • UseFileServer is a combination that serves static files, enables directory browsing, and serves default files.

When configuring your application, choosing the middleware that aligns with your specific requirements for serving static content while considering security and performance implications is important.

In the next article, we 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 have your feedback about 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. 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 *