By admin / 19-Apr-2022 / in Blog, ASP.NET Core / 730 Comments / 16 Likes / Share This Post

Middleware in ASP.NET Core controls how our application responds to HTTP requests. It can also control how our application looks when there is an error, and it is a key piece in how we authenticate and authorize a user to perform specific actions.

ASP.NET Core Middleware with Examples

In this Video, I am going to discuss the ASP.NET Core Middleware with Examples. Please read our previous Video before proceeding to this Video where we discussed the ASP.NET Core appsettings.json file. As part of this Video, we are going to discuss the following concepts related to the ASP.NET Core Middleware Components.

  1. What are the ASP.NET Core Middleware Components?
  2. Where we use the Middleware Components in the ASP.NET Core application?
  3. How to Configure Middleware Components in ASP.NET Core application?
  4. Examples of using Middleware Components?
  5. What is the Execution Order of Middleware Components in ASP.NET Core?
  6. What are Request Delegates in ASP.NET Core?
  7. What is Use, Run, and Map method in ASP.NET Core?
  8. What is UseDeveloperExceptionPage Middleware Component?
  9. How to Configure Middleware Components using the Run() and Use() extension methods?
  10. What is the difference between MapGet and Map method?

What are the ASP.NET Core Middleware Components?

The ASP.NET Core Middleware Components are the software components (technically components are nothing but the C# Classes) that are assembled into the application pipeline to handle the HTTP Requests and Responses. Each middleware component in ASP.NET Core Application performs the following tasks.

  1. Chooses whether to pass the HTTP Request to the next component in the pipeline. This can be achieved by calling the next() method within the middleware.
  2. Can perform work before and after the next component in the pipeline.

In ASP.NET Core there are so many built-in Middleware components that are already made available that you can use directly. If you want then you can also create your own Middleware components in asp.net core applications. The most important point that you need to keep in mind is, in ASP.NET Core a given Middleware component should only have a specific purpose i.e. single responsibility.

Where we use Middleware Components in the ASP.NET Core application?

Some of the examples of using Middleware components in the ASP.NET Core application are as follows

  1. We may have a Middleware component for authenticating the user
  2. Another Middleware component may be used to log the request and response
  3. Similarly, we may have a Middleware component that is used to handle the errors
  4. We may have a Middleware component that is used to handle the static files such as images, Javascript or CSS files, etc.
  5. Another Middleware component may be used to Authorize the users while accessing a specific resource

The Middleware components are the components that we generally use to set up the request processing pipeline in the ASP.NET Core application. If you have worked with previous versions of. NET Framework then you may know, we use HTTP Handlers and HTTP Modules to set up the request processing pipeline. It is this pipeline that will determine how the HTTP request and response are going to be processed.

How to Configure Middleware Components in ASP.NET Core application?

In the ASP.NET Core application, we need to configure the Middleware components within the Configure() method of the Startup class which is present inside the Startup.cs file. This is the class that is going to run when the application starts. When we create an ASP.NET Core application with Empty Template, then by default the Startup class is created with the Configure() method as shown in the below image.

So, whenever you want to configure any middleware components in any type of .net core applications, then you need to configure it within the Configure() method of the Startup class by calling the Use* methods on the IApplicationBuilder object. As you can see in the above image, the Configure() method sets up the request processing pipeline with just three middleware components are as follows.

  1. UseDeveloperExceptionPage() Middleware component
  2. UseRouting() Middleware component
  3. UseEndpoints() Middleware component

Before understanding the above three built-in Middleware components. Let us first understand what are Middleware components and how exactly these Middleware components work in an ASP.NET Core application.

Understanding Middleware Components in ASP.NET Core:

In the ASP.NET Core application, the Middleware component can have access to both the incoming HTTP Request and outgoing HTTP Response. So, a Middleware component in ASP.NET Core can

  1. Handle the incoming HTTP request by generating an HTTP response.
  2. Process the incoming HTTP request, modify it, and then pass it to the next middleware component
  3. Process the outgoing HTTP response, modify it, and then pass it on to either the next middleware component or to the ASP.NET Core web server.

For better understanding, please have a look at the following diagram which shows how the middleware components used in the request processing pipeline of an ASP.NET Core application.

As shown in the above image, we have a logging middleware component. This component simply logs the request time and then passes the request to the next middleware component i.e. Static Files Middleware component in the request pipeline for further processing.

A middleware component in ASP.NET Core may also handle the HTTP Request by generating an HTTP Response. The ASP.NET Core Middleware component may also decide not to call the next middleware component in the request pipeline. This concept is called short-circuiting the request pipeline.

For example, we have a static file middleware component. And if the incoming HTTP request comes for some static files such as images, CSS files, JavaScript, etc. then this Static Files Middleware component can handle the request and then short-circuit the request pipeline by not calling to the next component in the pipeline i.e. the MVC Middleware component.

As we already discussed the ASP.NET Core middleware components can have access to both the HTTP request and response in the pipeline. So, a middleware component can also process the outgoing response. For example, the logging middleware component in our case may log the time when the response is sent back to the client.

What is the Execution Order of Middleware Components in ASP.NET Core Application?

It is very important to understand the execution order of Middleware components. The ASP.NET Core middleware components are executed in the same order as they are added to the pipeline. So, we need to take care when adding the middleware components to the request processing pipeline.

As per your applications business requirements, you may add any number of Middleware components. For example, if you are developing a static web application with some static HTML pages and images, then you may require only “StaticFiles” middleware components in the request processing pipeline.

But, if you are developing a secure dynamic data-driven web application then you may require several middleware components such as Logging Middleware, Authentication middleware, Authorization middleware, MVC middleware, etc.

What are Request Delegates in ASP.NET Core?

In ASP.NET Core, Request delegates are used to build the request pipeline i.e. request delegates are used to handle each incoming HTTP request. In ASP.NET Core, you can configure the Request delegates using the Run, Map, and Use extension methods. You can specify a request delegate using an in-line anonymous method (called in-line middleware) or you can specify the request delegates using a reusable class. These reusable classes and in-line anonymous methods are called middleware or middleware components. Each middleware component in the request processing pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline by not calling the next middleware component.

What is the use of the Use and Run method in ASP.NET Core Web Application?

In ASP.NET Core, you can use the “Use” and “Run” extension methods to register the Inline Middleware component into the Request processing pipeline. The “Run” extension method allows us to add the terminating middleware (the middleware which will not call the next middleware components in the request processing pipeline). On the other hand, the “Use” extension method allows us to add the middleware components which may call the next middleware component in the request processing pipeline.

If you observe the Configure method, then you will see that it gets an instance of the IApplicationBuilder interface and using that instance along with the extension methods such as Use and Run, it configures the Middleware components.

As you can see, in the configure method, three middleware components are registered in the request processing pipeline using the IApplicationBuilder instance i.e. app. They are as follows

  1. UseDeveloperExceptionPage() Middleware component
  2. UseRouting()
  3. UseEndpoints() Middleware component

DeveloperExceptionPage Middleware Component:

As you can see, within the configure method, the UseDeveloperExceptionPage() middleware component is registered into the pipeline and this middleware component will come into the picture only when the hosting environment is set to “development”. This middleware component is going to execute when there is an unhandled exception occurred in the application and since it is in development mode, it is going to show you the culprit line of code. You can consider this as a replacement for the yellow screen of death. In a later Video, we will see the use of this middleware component in detail with examples.

UseRouting() Middleware Component:

This middleware component is used to add Endpoint Routing Middleware to the request processing pipeline i.e. it will map the URL (or incoming HTTP Request) to a particular resource. We will discuss this in detail in our Routing Videos.

UseEndpoints() Middleware Component:

In this middleware, the routing decisions are going to be taken using the Map extension method. Following is the default implementation of UseEndpoints middleware components. In the MapGet extension method, we have specified the URL pattern like “/”. This means the domain name only. So, any request with only the domain name is going to be handle by this middleware.

Instead of MapGet, you can also use the Map method as shown below.

Now run the application and you should get the output as expected.

What is the difference between MapGet and Map method?

The MapGet method is going to handle the GET HTTP Requests whereas the Map method is going to handle all types of HTTP requests such as GET, POST, PUT, & DELETE, etc.

How to Configure Middleware Components using the Run() extension method?

Let us understand how to create and configure custom middleware components using the Run extension method. First of all, comment on all codes which are present inside the Configure method. Once you comment on the existing code, then copy and paste the following code into the Configure method. The following code simply adds a new middleware component to the applications request pipeline and simply prints a message.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

app.Run(async (context) =>

{

await context.Response.WriteAsync(“Getting Response from First Middleware”);

});

}

Output:

We are invoking the Run() extension method on the IApplicationBuilder instance (app) to register the middleware component into the request processing pipeline. Following is the definition of the Run method.

As you can see from the definition of the Run() method, it is implemented as an extension method of the IApplicationBuilder interface. This is the reason why we are able to call the Run() method using the IApplicationBuilder instance i.e. app. If you are new to the extension method then please read the below Video where we discussed the extension methods in detail.

https://dotnettutorials.net/lesson/extension-methods-csharp/

You can also see from the above image that the Run() method takes an input parameter of type RequestDelegate. Following is the definition of RequestDelegate.

As you can see from the above image, the RequestDelegate is a delegate that takes an input parameter of type HttpContext object. If you are new to delegates then I strongly recommended you read the following Video where we discussed the delegates in detail.

https://dotnettutorials.net/lesson/delegates-csharp/

As we already discussed the middleware components in the ASP.NET Core application can have access to both HTTP Request and Response and this is because of the above HttpContext object.

In our example, we are passing the request delegate inline as an anonymous method using lambda expression and moreover, we are passing the HTTPContext object as an input parameter to the request delegate. The following diagram shows the above

Note: Instead of passing the request delegate inline as an anonymous method, you can also define the request delegate in a separate class and pass it here which we will discuss in a later Video.

Add one more middleware to the application.

To do so, modify the configure method of the Startup class as shown below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

app.Run(async (context) =>

{

await context.Response.WriteAsync(“Getting Response from First Middleware”);

});

app.Run(async (context) =>

{

await context.Response.WriteAsync(“Getting Response from Second Middleware”);

});

}

Now we have two middleware components registered with the Run() extension method. If you run the application then you will get the following output.

Getting Response from 1st Middleware

The output is coming from the first middleware component. The reason is, when we registered a middleware component using the Run() extension method then that component becomes a terminal component means it will not call the next middleware component in the request processing pipeline.

Configuring middleware component using the Use extension method

Then the question that comes to your mind is how to call the next component in the request processing pipeline, the answer is to register your middleware component using the Use extension method as shown below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

app.Use(async (context, next) =>

{

await context.Response.WriteAsync(“Getting Response from 1st Middleware”);

await next();

});

app.Run(async (context) =>

{

await context.Response.WriteAsync(“Getting Response from 2nd Middleware”);

});

}

Now run the application and you will see the output as expected which is coming from both the middleware components.

Understanding the Use extension method:

The Use extension method adds a middleware delegate defined in-line to the applications request pipeline. Following is the definition of the Use extension method:

This method is also implemented as an extension method on the IApplicationBuilder interface. This is the reason why we are able to invoke this method using the IApplicationBuilder instance. As you can see from the above definition, this method takes two input parameters. The first parameter is the HttpContext context object through which it can access both the HTTP request and response. The second parameter is the Func type i.e. it is a generic delegate that can handle the request or call the next middleware component in the request pipeline.

Note: If you want to send the request from one middleware to the next middleware then you need to call the next method.

READ MORE

SEE ALL

COMMENTS (730 COMMENTS)

SUBMIT YOUR COMMENT

SEND COMMENT

SEE ALL POSTS

RELATED POSTS

ASP.NET Core / Blog

What is ASP.NET Core?

ASP.NET Core is the new version of the ASP.NET web framework mainly targeted to run on .NET Core platform.

27-jan-2022 /16 /730

ASP.NET Core / Blog

What is ASP.NET Core Framework?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps. With ASP.NET Core, you can: Build web apps and services, Internet of Things (IoT) apps, and mobile backends. Use your favorite development tools on Windows, macOS, and Linux.

27-jan-2022 /16 /730

ASP.NET Core / Blog

How to Setup ASP.NET Core Environment ?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps. With ASP.NET Core, you can: Build web apps and services, Internet of Things (IoT) apps, and mobile backends. Use your favorite development tools on Windows, macOS, and Linux.

27-jan-2022 /16 /730

--

--

Connektteacher

Welcome to Connekt Teacher Digital Library. Free Online Tutorials and Courses. The Complete Developer Course 2022 Videos.