[go: up one dir, main page]

0% found this document useful (0 votes)
12 views36 pages

Core 5

The ASP.NET Core Request Processing Pipeline consists of middleware components that manage HTTP requests and responses in a web application, performing tasks like authentication, routing, and logging. Middleware is configured in the Program class, and the order of middleware execution is crucial for application functionality. Additionally, the wwwroot folder serves as the web root for static files, which can be accessed directly by clients, and the Static Files Middleware is required to serve these files.

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views36 pages

Core 5

The ASP.NET Core Request Processing Pipeline consists of middleware components that manage HTTP requests and responses in a web application, performing tasks like authentication, routing, and logging. Middleware is configured in the Program class, and the order of middleware execution is crucial for application functionality. Additionally, the wwwroot folder serves as the web root for static files, which can be accessed directly by clients, and the Static Files Middleware is required to serve these files.

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

ASP.

NET Core Request Processing Pipeline

Here I will discuss the ASP.NET Core Request Processing Pipeline with Examples.

What is the ASP.NET Core Request Processing Pipeline?pcoming

The ASP.NET Core request processing pipeline is a series of middleware components that handle incoming HTTP
requests and responses in an ASP.NET Core Web application. Each middleware component in the request
processing pipeline is responsible for a specific task, such as authentication, routing, logging, caching, encryption
and decryption, response generation, etc. The pipeline is configured in the Program class of an ASP.NET Core
application.

How Does the ASP.NET Core Request Processing Pipeline Work?

The ASP.NET Core Request Processing Pipeline is a series of middleware components that handle HTTP requests
and responses. Let us proceed and understand how the ASP.NET Core Request Processing Pipeline Works:

Hosting: ASP.NET Core applications start with a host, which is responsible for application startup and lifetime
management. The host sets up the web server (like Kestrel or IIS) to handle incoming HTTP requests.

Middleware: Middleware components are the basic building blocks of the request processing pipeline. Each
middleware component handles HTTP requests and can perform operations such as authentication, logging, and
routing. Middleware can also short-circuit the pipeline by not calling the next middleware in the sequence.

Request Processing Flow of ASP.NET Core Web Application

The typical flow of an HTTP request process through the pipeline is as follows:

HTTP Server (Kestrel/IIS): The HTTP server (e.g., Kestrel or IIS) receives the request and forwards it to the
ASP.NET Core application.

Middleware Execution: Each middleware component processes the request in the order they are added in the
Program class. Middleware components can perform various tasks, such as:

 Routing: Determines the endpoint that should handle the request.


 Authentication: Validates user credentials and establishes user identity.
 Authorization: Checks if the authenticated user has permission to access the requested resource.
 Error Handling: Catches and handles exceptions that occur during request processing.
 Static Files: Serves static files such as HTML, CSS, and JavaScript.
 Endpoint Execution: If the request reaches the endpoint middleware, the corresponding controller
action or Razor Page is executed to generate a response.
Response Handling: The response flows back through the middleware pipeline, allowing each middleware to
modify it if necessary.

Common Middleware Components in ASP.NET Core

The following are some of the commonly used middleware components in ASP.NET Core Web Application to
manage the Request Processing Pipeline:

 Routing Middleware: Determines the endpoint that matches the request URL and invokes it.
 Authentication Middleware: Handles user authentication.
 Authorization Middleware: Enforces access control policies.
 Static File Middleware: Serves static files.
 Exception Handling Middleware: Captures and handles exceptions.
 Logging Middleware: Logs request and response information.
 CORS Middleware: Enforces Cross-Origin Resource Sharing (CORS) policies.
Example to Understand ASP.NET Core Request Processing Pipeline

To understand the Request Processing Pipeline, first, let us modify the Main() Method of the Program class as
shown below. Here, we are registering three middleware components into the Request Processing Pipeline. As
you can see, the first two Middleware Components are registered using the Use() Extension Method so that they
have the chance to call the next Middleware Component in the Request Processing Pipeline. The last one is
registered using the Run() Extension Method as it will be our terminating components, i.e., it will not call the next
component.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
//Configuring Middleware Component using Use and Run Extension Method
//First Middleware Component Registered using Use Extension Method
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Middleware1: Incoming Request\n");
//Calling the Next Middleware Component
await next();
await context.Response.WriteAsync("Middleware1: Outgoing Response\n");
});
//Second Middleware Component Registered using Use Extension Method
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Middleware2: Incoming Request\n");
//Calling the Next Middleware Component
await next();
await context.Response.WriteAsync("Middleware2: Outgoing Response\n");
});
//Third Middleware Component Registered using Run Extension Method
app.Run(async (context) =>
{
await context.Response.WriteAsync("Middleware3: Incoming Request handled and response generated\n");
//Terminal Middleware Component i.e. cannot call the Next Component
});
//This will Start the Application
app.Run();
}
}
}
Now run the application, and you should get the following output in the browser.

Understanding Request Processing Pipeline Execution Order:

Let us compare the above output with the following diagram to understand the ASP.NET Core Request Processing
Pipeline in an easier way.

When the incoming HTTP request arrives, it is first received by the first middleware component, Middleware1,
which logs “Middleware1: Incoming Request” in the response stream. As a result, we first see this message on
the browser. Once the first middleware logs the information, it calls the next() method, invoking the second
middleware in the request processing pipeline, Middleware2.

The second middleware logs the information “Middleware2: Incoming Request”. As a result, we see this log
information after the first log. Then, the second middleware calls the next(), invoking the third middleware in the
request processing pipeline, Middleware3.

The third middleware handles the request and then produces the response. So, the third information that we see
in the browser is “Middleware3: Incoming Request handled and response generated”.

The third middleware component is registered using the Run() Extension Method and is a terminal middleware
component. So, from this point, the request pipeline starts reversing. That means the control is returned to the
second middleware from this middleware. The second middleware logs the information as “ Middleware2:
Outgoing Response” and then gives the control back to the first middleware component, and the first
middleware component logs the information as “Middleware1: Outgoing Response” as we see in the browser.

Key Points to Remember:

1. The ASP.NET Core Request Processing Pipeline consists of a sequence of Middleware Components that
will be called one after the other.
2. Each Middleware Component can perform some operations before and after invoking the next
Middleware Component using the next method. A middleware component can also decide not to call
the next middleware component, which is called short-circuiting the request pipeline.
3. The Middleware Component in ASP.NET Core has access to both the incoming request and the outgoing
response.
4. The most important point is that the order in which the Middleware Components are added in the Main
method of the Program class defines the order in which these Middleware Components will be invoked
on requests and the reverse order for the response. So, the order is important for defining the
application’s Security, Performance, and Functionality.

wwwroot Folder in ASP.NET Core

Here I will discuss wwwroot Folder in ASP.NET Core Application.

What is wwwroot Folder in ASP.NET Core?

By default, the wwwroot folder in the ASP.NET Core Web Application is treated as the Web Root folder, and this
folder or directory should be present in the project root directory.

The wwwroot folder in ASP.NET Core is a standard folder that serves as the web root or the root directory from
which static files are served to the clients. Files in this directory can be served directly to clients. These files can
include images, CSS files, JavaScript files, and other static content.

Key Characteristics of wwwroot Folder in ASP.NET Core:

The following are some of the Key Characteristics of wwwroot Folder in ASP.NET Core Web Application:

 Accessibility: Files placed in the wwwroot folder are served directly to clients without any processing
from ASP.NET Core. This makes them efficient for serving static content.
 Default Location: In an ASP.NET Core project, the wwwroot folder is located at the root level alongside
other project folders like Controllers, Views, and Models.
 Accessing Files: You can access files in the wwwroot folder using relative URLs in your web pages. For
example, if you have a file named styles.css in wwwroot/css, you can reference it in your HTML using
http://<your-app-url>/css/styles.css.
 Static Files Middleware: ASP.NET Core includes UseStaticFiles middleware to serve static files from the
wwwroot folder.
 Security: The wwwroot directory provides security for your application. Files outside this directory are
not accessible via a direct URL, helping to protect application code and data.
Adding the wwwroot (webroot) folder in the ASP.NET Core Application:

When we create a new ASP.NET Core Web Application with MVC or Razor Pages Project Template, then by
default, this folder (wwwroot) is created in the project root directory. But if you create a new ASP.NET Core
Application with Empty Project Template, then by default, this folder will not be created by Visual Studio.

As we are discussing everything from scratch, let us create a new ASP.NET Core Application using the Empty
Project template and then understand how to add the wwwroot folder to it.

Creating a new ASP.NET Core Empty Web 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 the Create a new project tab, as shown in the image
below.
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.

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.

Once you click on the Next button, the Additional Information window will open. Here, you need to select .NET 8
as the Framework, check the Configure for HTTPS, Do not use top-level statements check boxes, and finally, click
the Create button, as shown in the image below.
Once you click the Create button, a new ASP.NET Core Web Application will be created in Visual Studio 2022. The
project will have the following file and folder structure.

As you can see in the above image, there is no such folder called wwwroot in our application.

Adding wwwroot (webroot) Folder in ASP.NET Core:

To add the wwwroot folder, right-click on the project, select the add => new folder option from the context
menus, and then provide the folder name as wwwroot. Once you create the folder, please look at the folder
symbol, which should be displayed as a web symbol, as shown below.

What is the wwwroot (webroot) folder going to contain in ASP.NET Core?

Generally, there should be separate folders for the different types of static files, such as JavaScript, CSS, Images,
Library Scripts, etc, inside the wwwroot folder as shown below:
Now, you can access static files such as CSS, JS, and lib with the base URL and file name. For example, you can
access the above site.js file from the js folder by https://localhost:<port>/js/site.js

Note: To Serve the Static Files, you must include the UseStaticFiles() Middleware component in the Main()
method of the Program.cs class file.

Understanding WebApplicationOptions Class in ASP.NET Core:

In ASP.NET Core, the WebApplicationOptions class plays an important role in configuring the properties of a
WebApplicationBuilder, which is used to create an instance of a WebApplication. So, using the
WebApplicationOptions Class, we can set and get the Application Environment Name, Application Name, Web
Root Path, Content Root Path, etc. If you go to the definition of the WebApplicationOptions class, then you will
see the following.

The meaning of each property is as follows:

 ApplicationName: The ApplicationName property of the WebApplicationOptions class is used to get or


set the name of the application. This is used in various parts of the framework where an application
name is required, like logging, caching, etc.
 ContentRootPath: The ContentRootPath property of the WebApplicationOptions class sets the absolute
path to the directory containing the application content files, i.e., the application’s root directory. It is
the base path for locating content files, such as configuration and data files (e.g., appsettings.json,
and .cshtml files for Razor Pages).
 EnvironmentName: The EnvironmentName property of the WebApplicationOptions class specifies the
environment in which the application is running. This could be Development, Staging, and Production.
This is important for enabling environment-specific configurations or behaviors.
 WebRootPath: The WebRootPath specifies the path to the root directory of static content, commonly
known as the wwwroot folder in ASP.NET Core projects. This directory contains static files like HTML,
CSS, JavaScript, and images.
 Args: This property represents the command-line arguments passed to the application. It’s an array of
strings (string[]).
Now, modify the Main method of the Program class as follows. Here, we display the default EnvironmentName,
ApplicationName, WebRootPath, and ContentRootPath.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => $"EnvironmentName: {app.Environment.EnvironmentName} \n" +
$"ApplicationName: {app.Environment.ApplicationName} \n" +
$"WebRootPath: {app.Environment.WebRootPath} \n" +
$"ContentRootPath: {app.Environment.ContentRootPath}");
//This will Run the Application
app.Run();
}
}
}
Output:

Can we rename the wwwroot Folder in ASP.NET Core (.NET 6)?

Yes. We can rename the wwwroot folder to any other name and set it as the webroot while preparing the
hosting environment in the Program.cs file. In that case, we need to use the other overloaded version of
the CreateBuilder method, which takes the WebApplicationOptions instance as a parameter.

So, we need to create an instance of the WebApplicationOptions class. While creating the instance or once the
instance is created, we need to set the WebRootPath property or any other properties like Args,
ContentRootPath, EnvironmentName, etc. Then, we need to pass this instance to the CreateBuilder method.

For example, let’s rename the wwwroot folder to the MyWebRoot folder. Once you rename the wwwroot folder
to MyWebRoot, you need to set the WebRootPath property of the WebApplicationOptions instance
to MyWebRoot. Then, you need to pass this WebApplicationOptions instance to the CreateBuilder method.

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)
{
//Step1: Creating an Instance of WebApplicationOptions Class
WebApplicationOptions webApplicationOptions = new WebApplicationOptions
{
WebRootPath = "MyWebRoot", //Setting the WebRootPath as MyWebRoot
Args = args, //Setting the Command Line Arguments in Args
EnvironmentName = "Production", //Changing to Production
};
//Step2: Pass WebApplicationOptions Instance to the CreateBuilder Method
var builder = WebApplication.CreateBuilder(webApplicationOptions);
var app = builder.Build();
app.MapGet("/", () => $"EnvironmentName: {app.Environment.EnvironmentName} \n" +
$"ApplicationName: {app.Environment.ApplicationName} \n" +
$"WebRootPath: {app.Environment.WebRootPath} \n" +
$"ContentRootPath: {app.Environment.ContentRootPath}");
//This will Run the Application
app.Run();
}
}
}
Output:

As you can see in the above output, the MyWebRoot folder will now act as the Webroot folder for our
application and can serve the static files.

Static Files Middleware in ASP.NET Core Application

Here I will discuss how to Serve Static Files using Static Files Middleware in an ASP.NET Core Web Application
with Examples.

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?

Static Files Middleware in ASP.NET Core Web Application:

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 a
Web Application, and ASP.NET Core can serve these files directly to the clients. However, the important point you
need to remember is that ASP.NET Core cannot serve these static files by default. Some configuration is required
to enable ASP.NET Core to serve these static files directly. The Static Files Middleware is responsible for handling
static files and making them accessible to clients.

In the ASP.NET Core Application, the default directory or location for the static files is the wwwroot (webroot)
folder, which should be present in the project root directory. By default, this is the only place where the ASP.NET
Core application can serve the static files directly. However, we can change this default behavior using
the WebApplicationOptions Instance and WebRootPath property.

Example to understand Static Files in .NET Application:

When we create a new ASP.NET Core Application 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.

As you can see in the above image, our application does not have a folder called wwwroot. However, if you
create the Project using the MVC (Model-View-Controller) Project Template, Visual Studio will create the
wwwroot folder by default.

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 shown below.

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

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

Now run the application and navigate to the following URL. 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.

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 We Configure the Static Files Middleware in ASP.NET Core Application?

To handle the static resources in the ASP.NET Core Web Application, we need to configure a middleware
called UseStaticFiles() into the application Request Processing Pipeline. The UseStaticFiles() middleware is an
inbuilt Middleware 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 register the UseStaticFiles()
Middleware Component in the application’s Request Processing Pipeline. This method should be placed before
any middleware that requires access to the static files (such as MVC middleware if you’re using it).

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 Do We Create Our Own Webroot Folder in ASP.NET Core?

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.

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

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 serve 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. So, we need to set the WebRootPath property to MyWebRoot while
creating the WebApplicationBuilder instance. 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();
}
}
}

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.

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.

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.

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.
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.

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.

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 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.

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

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.

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.
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.
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.

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.

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.

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.

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.

Developer Exception Page Middleware in ASP.NET Core Application

Here I will discuss How to Handle an Unhandled Exception using the Developer Exception Page Middleware
Component in an ASP.NET Core Web Application.

Exception Handling is one of the key features of any application. We can handle the exception in many different
ways. However, in this article, I will discuss how we can use the Developer Exception Page Middleware
Component to handle the unhandled exception in the ASP.NET Core Web Application. As part of this article, we
will discuss the following concepts.

1. What is Developer Exception Page Middleware?


2. How do you use Developer Exception Page Middleware in ASP.NET Core Application?
3. How do you customize the UseDeveloperExceptionPage Middleware in ASP.NET Core?
4. Where do we need to configure the UseDeveloperExceptionPage Middleware?

Developer Exception Page Middleware in ASP.NET Core

The Developer Exception Page Middleware in the ASP.NET Core Application diagnoses issues during the
development phase. It provides detailed information about exceptions, which can help us quickly identify and
resolve problems. However, it is used only in the development environment, as exposing detailed error
information in production can be a security risk.

The Developer Exception Page Middleware captures unhandled exceptions from the pipeline and generates
HTML error responses with detailed information, including stack traces, source code snippets, and other relevant
data. We can also customize the Developer Exception Page Middleware component.
Imagine you have an ASP.NET Core Web API project and encounter an issue where an API endpoint throws an
unhandled exception. With the Developer Exception Page Middleware enabled, you can see exactly where the
exception occurred, inspect the request details, and view the stack trace to diagnose the issue effectively.

Understanding Developer Exception Page Middleware in ASP.NET Core:

Let us understand Developer Exception Page Middleware in ASP.NET Core Applications with some examples.
First, create a new ASP.NET Core Application using the Empty Project template. By default, the ASP.NET Core
Web Application (.NET 8) registers the Developer Exception Page Middleware Component into the Request
Processing Pipeline in the Development Environment, and if any unhanded exception occurs, then it will return
the exception detail page using the Developer Exception Page middleware. Let us understand this with an
example. Please modify the Main() method of the Program Class as shown below, where we throw an exception
from the MapGet endpoint.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", async context =>
{
int Number1 = 10, Number2 = 0;
int Result = Number1 / Number2; //This statement will throw Runtime Exception
await context.Response.WriteAsync($"Result : {Result}");
});
//This will Run the Application
app.Run();
}
}
}
When you run the application, you will get the following output.
As you can see, the above page displays the exception details. This is because the .NET Core Framework
automatically enables the Developer Exception Page Middleware Component for the Development environment.
You can also manually add the Developer Exception Page Middleware component within the Program class’s
Main method.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
//If the Environment is Development, Please Show the Unhandled Exception Details
if (app.Environment.IsDevelopment())
{
//Using UseDeveloperExceptionPage Middleware to Show Exception Details
app.UseDeveloperExceptionPage();
}
app.MapGet("/", async context =>
{
int Number1 = 10, Number2 = 0;
int Result = Number1 / Number2; //This statement will throw Runtime Exception
await context.Response.WriteAsync($"Result : {Result}");
});
//This will Start the Application
app.Run();
}
}
}
With this change, run the application, and you will also get the same exception page as shown in the below
image.
As you can see in the above image, the Developer Exception Page contains five tabs: Stack, Queue, Cookies,
Headers, and Routing. Let us understand these tabs in detail:

Stack

The Stack tab displays the stack trace of the exception. That means it shows a detailed stack trace of the
exception, including method names, file names, and line numbers.

This tab is important for tracing the execution path, understanding the program’s flow up to the point of failure,
and identifying the exact location in the code where the exception was thrown. This information is important for
understanding the exact point in your code where the error has occurred.

Query

The Query tab shows the query string parameters of the HTTP request that resulted in the exception. Query
strings are a way to pass data to the server as part of the URL. This includes parameters typically found in the URL
after the “?” symbol.

This tab is useful for verifying the presence and correctness of query parameters and debugging issues related to
filtering, searching, or other functionalities that rely on query string parameters.

Cookies

The Cookies tab lists all cookies sent with the HTTP request. Cookies are key-value pairs used primarily to
maintain the session state and store small amounts of data on the client side.

This tab is used to check if cookies relevant to the exception are present and correctly formatted. This can help
diagnose issues related to user sessions, authentication, or other state management mechanisms.

Headers

The Headers tab lists all HTTP headers sent by the client in the request and the headers that were part of the
response. HTTP headers let the client and the server pass additional information with an HTTP request or
response. This includes headers such as User-Agent, Accept, Host, and custom headers specific to your
application.

This tab is useful for verifying the presence and values of headers that might affect your application’s behavior. It
can also help troubleshoot issues related to content negotiation, authentication, or other header-dependent
functionalities.

Routing

The Routing tab displays information about the routing process. It shows the route that matched the incoming
request and how the request was routed to a particular endpoint. This includes information about route patterns,
values, and matched endpoints.

This tab ensures the request was routed correctly and diagnoses routing-related issues, such as incorrect route
patterns or endpoint mismatches.

How do you customize the UseDeveloperExceptionPage Middleware in ASP.NET Core?

We can customize the UseDeveloperExceptionPage middleware component to provide more detailed error
information in the development environment. This can be useful for adding additional debugging information,
changing the layout, or styling. To do so, we need to use the DeveloperExceptionPageOptions.
The point that you need to remember is whenever we want to customize a middleware component in ASP.NET
Core, we need to use the respective Options object. For example

1. UseDeveloperExceptionPage => To customize UseDeveloperExceptionPage middleware, use


the DeveloperExceptionPageOptions object.
2. UseDefaultFiles => To customize UseDefaultFiles middleware, use the DefaultFilesOptions object
3. UseStaticFiles => To customize UseStaticFiles middleware, use the StaticFileOptions object
4.
UseFileServer => To customize UseFileServer middleware, use the FileServerOptions object
So, please modify the Main method of the Program class as shown below to customize the
UseDeveloperExceptionPage middleware component. The following code is self-explained, so please read 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();
//If the Environment is Development, Please Show the Unhandled Exception Details
if (app.Environment.IsDevelopment())
{
//Create an Instance of DeveloperExceptionPageOptions to Customize
//UseDeveloperExceptionPage Middleware Component
DeveloperExceptionPageOptions developerExceptionPageOptions = new DeveloperExceptionPageOptions
{
SourceCodeLineCount = 5
};
//Passing DeveloperExceptionPageOptions Instance to UseDeveloperExceptionPage Middleware Component
app.UseDeveloperExceptionPage(developerExceptionPageOptions);
}
app.MapGet("/", async context =>
{
int Number1 = 10, Number2 = 0;
int Result = Number1 / Number2; //This statement will throw Runtime Exception
await context.Response.WriteAsync($"Result : {Result}");
});
//This will Start the Application
app.Run();
}
}
}
As you can see in the above code, we are using one property
called SourceCodeLineCount. The SourceCodeLineCount property of the DeveloperExceptionPageOptions class
specifies the number of lines of code to include before and after the line of code that caused the exception.

Now, if you run the application with the above changes in place, you will get the following error: Please have a
look at error line 28 and the number of lines before and after it.

Note: From .NET 6, explicitly configuring the developer exception page middleware is unnecessary. By default,
the Framework will load the developer exception page if the environment is Development.

Best Practices to Use Developer Exception Page Middleware

 Not for Production: Never use the Developer Exception Page Middleware in a production environment.
It can expose sensitive information about the application structure, database, etc.
 Combine with Logging: While this middleware is helpful for immediate debugging, it’s also important to
implement robust logging for exceptions to track and analyze errors at production.

ASP.NET Core Command Line Interface (.NET Core CLI)

Here I will discuss how to create, build, and run ASP.NET Core Applications using ASP.NET Core CLI (Command
Line Interface) Commands.

ASP.NET Core Command Line Interface:

The .NET Core CLI (Command Line Interface) is a new cross-platform tool for creating ASP.NET Core Applications,
Restoring Packages, Building, Running, and Publishing ASP.NET Core Applications. CLI commands work across
different platforms like Windows, macOS, and Linux. The .NET Core CLI command uses Kestrel as the only Web
Server that hosts and runs the application.

As of now, all the applications we created are using Visual Studio. Visual Studio internally uses the .NET CLI
commands to restore, build, and publish the applications. Other higher-level IDEs, editors, and tools like Visual
Studio Code use these CLI Commands to support creating, restoring, publishing, and running .NET Core
applications.

Key Features of .NET Core CLI:

 Project Creation: Using simple commands, we can create new .NET Core projects (like console apps, web
apps, and libraries). To get started quickly, it comes with templates for different types of applications.
 Building and Running: we can compile and execute .NET Core applications directly from the command
line, which is helpful for testing and development.
 NuGet Package Management: The CLI commands allow us to manage NuGet packages directly from the
command line. We can add, update, or remove packages.
 Publishing: We can also publish our applications using the CLI command, which includes compiling the
application and its dependencies into a set of files or a single executable file.
How to Install Command Line Interface?

When we installed the .NET Core SDK, the .NET Core CLI was also installed by default. So, we aren’t required to
install it separately in the development environment, i.e., on our local machine. We can verify whether the .NET
CLI is installed using the command prompt. To verify this, open the command prompt (Windows) or terminal
(Linux), type dotnet, and press enter, as shown below. If it displays usage and help options, as shown in the
image below, the .NET Core CLI is installed properly.

.NET Core CLI Command Structure:

The .NET Core CLI command structure is nothing but how we write the .NET Core CLI command. The following is
the command structure of .NET Core CLI Command:

dotnet <command> <argument> <option>

Here,

 dotnet: The base or driver command used to run the CLI.


 command: The specific command to perform a task (e.g., new, build, run).
 arguments: The arguments required by the command, such as project or solution name.
 options: Optional parameters that modify the command’s behavior (e.g., -o for output directory).
How to Get all .NET Core CLI Commands?

Open the command prompt, type dotnet help, and press the enter button to display all the .NET Core CLI
commands. Some of the commands and their uses are given below.
The following are some of the commonly used .NET CLI commands that are relevant to ASP.NET Core
development:

 dotnet new: This command is used to create a new .NET project, configuration file, solution, or
template. This command sets up a new project with all the necessary files based on the specified
template, such as a console app, web app, or class library.
 dotnet build: To compile a .NET project and all its dependencies into a set of binaries. The dotnet build
command is used to produce executable or library files, i.e., Intermediate Language (IL) code files from
source code.
 dotnet run: This command runs the .NET application directly from the source code. It implicitly calls
dotnet build if the project hasn’t been built previously.
 dotnet publish: This command packs the application and its dependencies into a folder for deployment
to a hosting environment.
 dotnet add package: This command is used to add a NuGet package reference to a project file. This
command facilitates the management of external libraries and tools, integrating them into a project
directly from the command line.
 dotnet remove package: To remove a NuGet package reference from a project file. This command is
used to manage dependencies by removing unnecessary or unused packages.
 dotnet restore: To restore the dependencies and tools specified in the project file(s). This is essential for
initializing a project or re-syncing the package references. This is usually done automatically when we
run dotnet build or dotnet run.
 dotnet clean: To clean the output of a project. This command clears the build artifacts (such as binaries
and obj files) from the output directory, which is useful for ensuring a clean rebuild of the project.

Create a New Project using the .NET Core CLI Command:

Let’s create, restore, build, and run the .NET Core console application using the command-line interface without
Visual Studio. To create a new .NET Core project, we need to use the ‘new’ command followed by the template
name argument. We can create the console, class library, web, web app, MVC, Web API, razor, angular, react,
etc. Project using CLI.

The following command creates a new dotnet core project using the TEMPLATE:
dotnet new <TEMPLATE>

You can find the list of templates using the following CLI Command:
dotnet new list

Once you type dotnet new list and press enter, it will show you the list of available templates based on the .NET
Core Version installed on your machine, as shown in the image below:
Example to Create a Console Application using .NET Core CLI

The following command creates a new console project with the same name (MyConsoleApp) in the current
directory. First, you create a folder called Projects in the D Drive. Inside this Projects folder, you need to create
another folder with the name MyConsoleApp. Then, as shown in the image below, you need to set the directory
path to D: ProjectsMyConsoleApp.

Then, you need to use the dotnet new console command to create the console application. Once you execute
the dotnet new console command, it will create a new console application and get the following output. Here,
the project is created with the name MyConsoleApp.
You can also give your project a different name if you want. For example, the following command will create a
new console project named MyConsoleApp1. The -n or –name option specifies the name of the project.

dotnet new console -n MyConsoleApp1

Once you execute the above command, it will create a new console application named MyConsoleApp1, and you
will get the following output.

If you want to create your project in a specific directory, use the following CLI Command. This command will
create a new console application called MyConsoleApp2 in the D:\\ MyProjects directory. The -o or —
output option lets you specify the output directory for the project. To execute this command, make sure you first
create a folder named MyProjects in your D drive.

dotnet new console -n MyConsoleApp2 -o D:\\MyProjects

Once you execute the above command, it will create a new console application named MyConsoleApp2 with
the D:\\ MyProjects directory, and you will get the following output.

After creating the project, navigate to the project directory (folder) in the command prompt to apply project-
specific commands. As we created the project in D:\\ MyProjects directory folder, then went to the D:\\
MyProjects directory in the command prompt, as shown below.
Add Package Reference using .NET Core CLI Command:

We often need to add NuGet package references for different purposes. For example, apply the following
command to add the Newtonsoft.json package to your console project.

dotnet add package Newtonsoft.json

You should get the following output once you type the above command and press enter.

This will add the Newtonsoft.json package to your project. You can verify this in the project file. So, open
the .csproj file in Notepad, and you should get the following.

Remove Package Reference using .NET Core CLI Command:

The dotnet remove package command removes a NuGet package reference from a project. If you want to
remove the NuGet Package that we just installed Newtonsoft.json, then you need to execute the below
command,

dotnet remove package Newtonsoft.json

So, in the command prompt, type “dotnet remove package Newtonsoft.json” and press the enter button as
shown in the image below, which will remove the Newtonsoft.json package from your project. You verify the
same in the project file.

Restore Packages using .NET Core CLI Command:

To restore packages or to update existing packages in your project, you can use the “dotnet restore” command
as below:
Build Project using .NET Core CLI Command:

To build a new or existing project, we need to use the “dotnet build” command as shown below, which will build
your .NET Core Project:

Run .NET Core Project using .NET Core CLI Command:

To run the .NET Core project, we need to use the “dotnet run” command, as shown below. Here, you can see the
output displayed: Hello World!

Project Templates in ASP.NET Core Application

Here I will discuss Project Templates in ASP.NET Core Applications.

Project Templates in ASP.NET Core Application

ASP.NET Core offers several project templates to help you get started with different types of web applications
and services. These templates are designed to provide a basic structure and include necessary dependencies and
configurations. They include a set of files and configurations that are designed to help you get started quickly
with a specific type of application. These templates provide a starting point for your projects, making setting up
the structure and dependencies you need easier.

Using ASP.NET Core, we can create different types of Web Applications. As you can see in the image below, while
creating an ASP.NET Core Web Application, we have different types of project templates for creating ASP.NET
Core Web applications.
So, let us discuss all these project templates a little. We will use these project templates in our upcoming articles
to build the ASP.NET Core Web application.

ASP.NET Core Empty Project Template:

As the name says, the ASP.NET Core Empty Project Template has no content by default. If you want to do
everything manually from scratch, then you need to select the Empty Project Template. The following image
shows the structure of an Empty template.

As you can see, the above project template contains the only basic files required for any ASP.NET Core Web
Applications. In this case, we need to add everything manually. To learn the basic concepts of ASP.NET Core, we
need to use ASP.NET Core Empty Project Template. In fact, as of now, we have used this ASP.NET Core Empty
Project Template to understand the basic concepts.

ASP.NET Core Web App Project Template

This project template creates an ASP.NET Core Web Application using ASP.NET Core Razor Page Content. The
Web Application Template uses the new Razor Pages Framework for building web applications. We need to use
this project template when we want to develop a web application but do not want the full complexity of ASP.NET
MVC. The following image shows the structure of the ASP.NET Core Web App Project Template.
ASP.NET Core Web App (Model-View-Controller) Project Template

The ASP.NET Core Web App (Model-View-Controller) Project Template contains everything that is required to
create an ASP.NET Core MVC Web Application. The ASP.NET Core Web App (Model-View-Controller) Project
Template creates folders for Models, Views, and Controllers. It also adds web-specific things such as JavaScript,
CSS files, Layout files, etc., which are necessary and required to develop a web application. The following image
shows the default file and folder structure of the ASP.NET Core Web App (Model-View-Controller) Project
Template.

ASP.NET Core Web API Project Template

The ASP.NET Core Web API Project Template contains everything required to create an ASP.NET Core RESTful
HTTP service. The following image shows the default structure of the ASP.NET Core Web API Project Template. As
you can see from the below image, it contains only the Controllers folder. The website-specific things such as CSS
files, JavaScript files, view files, layout files, etc., are absent. This is because an API has no user interface; hence, it
does not include such website-specific files. This API template also does not have the Models and Views folder, as
they are not required for an API.

You can also create the following Applications using ASP.NET Core.

 Angular, React, or React with Redux: These templates are set up to integrate with the respective
JavaScript frameworks/libraries. They include a basic setup that combines ASP.NET Core with Angular or
React for building rich client-side interfaces.
 Blazor Server: Used for creating interactive Web UIs using C# instead of JavaScript. It runs on the server
and communicates with the client side using SignalR.
 Blazor WebAssembly: This is similar to Blazor Server, but in this case, the application runs entirely on
the client side in the browser using WebAssembly.
 Worker Service: This template creates background services and long-running processes without a UI.
 Console App: This is for creating a console application using .NET Core.
 Class Library: This is used to create a reusable set of classes, interfaces, and other functionalities that
can be referenced from other applications.
Minimal Web API: Introduced in .NET 6, this template allows you to create a minimalistic Web API project with
fewer files and dependencies.

You might also like