0% found this document useful (0 votes)
4 views12 pages

Core 4

The document provides an overview of ASP.NET Core Middleware Components, detailing their role in the Request Processing Pipeline and how they manage HTTP requests and responses. It explains how to configure middleware components using various extension methods, such as Use, Run, and Map, and discusses the execution order and specific use cases for built-in middleware like authentication and error handling. Additionally, it highlights the differences between MapGet and Map methods, as well as how to create custom middleware components for specific application needs.

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)
4 views12 pages

Core 4

The document provides an overview of ASP.NET Core Middleware Components, detailing their role in the Request Processing Pipeline and how they manage HTTP requests and responses. It explains how to configure middleware components using various extension methods, such as Use, Run, and Map, and discusses the execution order and specific use cases for built-in middleware like authentication and error handling. Additionally, it highlights the differences between MapGet and Map methods, as well as how to create custom middleware components for specific application needs.

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/ 12

ASP.

NET Core Middleware with Examples

Here I will discuss the ASP.NET Core Middleware Components with Examples.

1. What are ASP.NET Core Middleware Components?


2. Where Do We Use Middleware Components in the ASP.NET Core Application?
3. How Do We Configure Middleware Components in .NET Applications?
4. How Does the Middleware Component Works in the ASP.NET Core Application?
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 the use of the Use and Run Extension Method in ASP.NET Core Web Application?
8. What is the Difference Between MapGet and Map Extension Methods in ASP.NET Core?
9. How Do We Configure Middleware Components Using the Run() Extension Method?
10. Adding Multiple Middleware Components into the Request Processing Pipeline
11. Configuring Middleware Components Using the Use Extension Method
12. Can we create a Terminal Middleware Component using the Extension method?
13. Differences Between Run, Map, and Use Extension Method in ASP.NET Core
What are ASP.NET Core Middleware Components?

ASP.NET Core Middleware Components are the basic building blocks of the Request Processing Pipeline in
ASP.NET Core Applications. The pipeline determines how the HTTP Requests and Responses will be processed in
the ASP.NET Core Application. Middleware components are used to implement various functionalities like
authentication, error handling, routing, and logging.

Middleware components are executed in the order they are added to the pipeline, and each middleware
component in the ASP.NET Core Application performs the following tasks.

 Chooses whether to pass the HTTP Request to the next Middleware component registered in the request
processing pipeline. This can be achieved by calling the next() method within the Middleware. In this
article, we will discuss how to register the Middleware component and call the next() method.
 Can perform certain tasks before and after the next component is invoked in the pipeline.
Note: In ASP.NET Core, many built-in Middleware components are already available for us to use directly. We can
also create our own middleware components per our business requirements. The most important point you need
to remember is that a given Middleware component should only have a specific purpose, i.e., a single
responsibility.

Where Do We Use Middleware Components in the ASP.NET Core Application?

Middleware components are used in the request processing pipeline of an ASP.NET Core application. They handle
cross-cutting concerns such as authentication, logging, error handling, routing, and more. Some examples of
using Middleware components in the ASP.NET Core application are as follows.

 UseAuthentication adds the authentication middleware to the ASP.NET Core pipeline. This middleware
is responsible for validating the credentials provided in requests and setting the user’s context.
 UseHttpsRedirection Middleware automatically redirects HTTP requests to HTTPS. This is important for
ensuring that all communications between the client and the server are encrypted and secure.
 UseDeveloperExceptionPage Middleware component provides a detailed error page in the browser
during development that shows stack traces, query parameters, cookies, and headers when an exception
occurs for easier debugging.
 UseExceptionHandler Middleware component captures and handles exceptions that occur during the
request processing, allowing us to provide custom error-handling logic for production environments. It
can help manage errors in production environments by redirecting to error pages or returning standard
error responses.
 UseStaticFiles Middleware enables our application to serve static files, like images, JavaScript, and CSS
files. It’s essential for delivering the static content of our web applications directly to clients.
 UseAuthorization adds authorization middleware to the ASP.NET Core pipeline. It checks whether the
authenticated user has permission to access a given resource or endpoint, which is necessary for
enforcing security policies in our application.
 UseRouting configures the routing middleware, enabling endpoint routing to map incoming requests to
the appropriate endpoint handlers based on route patterns defined in the application.
How Do We Configure Middleware Components in .NET Applications?

From the .NET 6, we need to configure the Middleware Components within the Main() method of the Program
class, which is present inside the Program.cs class file. As we already discussed, the application execution will
start with the Main method in the ASP.NET Core Web Application. When we create a new ASP.NET Core Empty
Web Application, the Program class is created with the Main method by default, as shown in the image below.

In the above Main method, we have configured two middleware components, MapGet and Run, by default. If
you want to configure a middleware component, you need to do so within the Main() method of
the Program class using the WebApplication instance.

For a better understanding, please modify the Main Method of the Program class as follows. Here, we have
configured a few Middleware Components using the WebApplication instance (using the variable app), such
as UseDeveloperExceptionPage(), UseRouting(), and MapGet().

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Initializes the configuration for the web application
var builder = WebApplication.CreateBuilder(args);
// Builds the web application based on the configured settings
var app = builder.Build();
// Middleware configuration section:
// Activates the Developer Exception Page in Development environment to show detailed error messages
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Adds the routing middleware to the request processing pipeline which is required to use the routing
capabilities
app.UseRouting();
// Endpoint configuration section:
// Maps HTTP GET requests to the root URL "/" to a method returning "Hello World!"
app.MapGet("/", () => "Hello World!");
// Maps HTTP GET requests to "/greet" URL to a method returning a greeting message
app.MapGet("/greet", () => "Hello from the /greet endpoint!");
// Maps HTTP GET requests to "/greet/{name}" URL to a method that uses a route parameter
app.MapGet("/greet/{name}", (string name) => $"Hello, {name}!");
// Starts the web application which begins listening for incoming requests
app.Run();
}
}
}
Before understanding the above Built-in Middleware Components (UseDeveloperExceptionPage(), UseRouting(),
and MapGet()) in ASP.NET Core Applications, let us first understand How Exactly These Middleware Components
are Executed and in what order in ASP.NET Core Web Applications.

How Does the Middleware Component Works in the ASP.NET Core Application?

In the ASP.NET Core Web Application, the Middleware Component can access the incoming HTTP Request and
outgoing HTTP Response. So, a Middleware Component in ASP.NET Core Web Application can

 Handle the incoming HTTP request by generating an HTTP response.


 Process the incoming HTTP request, modify it, and then pass it to the Next Middleware Component that
is configured in the Request Processing Pipeline.
 Process the outgoing HTTP response, modify it, and then pass it on to either the previous 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 are used in the Request Processing Pipeline of the ASP.NET Core Web Application. As shown in the
image below, we have configured 3 Middleware Components to the Application Request Processing Pipeline to
handle HTTP Requests and Responses.

We have a Logging Middleware Component. This component logs the request time and then passes the HTTP
Request to the next middleware component, i.e., the Static Files Middleware component in the Request Pipeline,
for further processing.

As previously discussed, a Middleware Component in an ASP.NET Core Web Application may also handle the
HTTP Request by generating an HTTP Response. The Middleware Component may also decide not to call the Next
Middleware Component in the Request Processing Pipeline, a concept called Short-Circuiting the Request
Processing Pipeline.
For example, we have a Static Files Middleware Component. Suppose the incoming HTTP request comes for some
static files such as images, CSS files, JavaScript, etc. In that case, this Static Files Middleware component can
handle the request and then Short-Circuiting the Request Processing Pipeline by not calling the Next Middleware
Component in the pipeline, i.e., the MVC Middleware Component.

The ASP.NET Core Middleware Components can access 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?

It is very important to understand the execution order of Middleware Components in ASP.NET Core Web
Applications. These components are executed in the same order as they are added to the Request Processing
Pipeline for incoming requests and in reverse order for outgoing responses. So, we need to take proper care
when adding the Middleware Components to the Request Processing Pipeline. If we add them in the wrong
order, then we might get unexpected behavior.

The following diagram shows the complete request processing pipeline for ASP.NET Core MVC and Razor Pages
apps. You have full control over reordering existing middleware or injecting new custom middleware as
necessary for your scenarios.

The order in which middleware components are added to the Program.cs file defines the order in which the
middleware components are invoked on requests and the reverse order for the response. The order is critical for
security, performance, and functionality.

What are Request Delegates in ASP.NET Core?

In ASP.NET Core, Request Delegates are used to build the Request Processing Pipeline, i.e., to handle each
incoming HTTP request. 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 specify the
Request Delegates using a reusable method (named method). These reusable methods and in-line anonymous
methods are called Middleware Components. Each Middleware Component in the Request Processing Pipeline is
responsible for invoking the Next Middleware 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 Extension Method in ASP.NET Core Web Application?

In the ASP.NET Core Web Application, we can use the “Use” and “Run” Extension Methods to register the Inline
Middleware Component. The “Run” extension method allows us to add the terminating middleware (the
middleware that 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 that are called the next
middleware component in the request processing pipeline.
If you observe the Main method of the Program class, using the WebApplication instance (app) along with the
extension methods such as Use and Run, we configure the Middleware Components.

If you further look at the Main method, then you will also see that using the MapGet extension method, we have
specified multiple URL patterns like “/”,”/ greet”,”/ greet/{name} “. So, based on the URL pattern, the
corresponding middleware component will be executed.

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

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Initializes the configuration for the web application
var builder = WebApplication.CreateBuilder(args);
// Builds the web application based on the configured settings
var app = builder.Build();
// Middleware configuration section:
// Activates the Developer Exception Page in Development environment to show detailed error messages
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Adds the routing middleware to the request processing pipeline which is required to use the routing
capabilities
app.UseRouting();
// Endpoint configuration section:
// Maps HTTP GET requests to the root URL "/" to a method returning "Hello World!"
app.Map("/", () => "Hello World!");
// Maps HTTP GET requests to "/greet" URL to a method returning a greeting message
app.Map("/greet", () => "Hello from the /greet endpoint!");
// Maps HTTP GET requests to "/greet/{name}" URL to a method that uses a route parameter
app.Map("/greet/{name}", (string name) => $"Hello, {name}!");
// Starts the web application which begins listening for incoming requests
app.Run();
}
}
}
What is the Difference Between MapGet and Map Extension Methods in ASP.NET Core?

In ASP.NET Core, both MapGet and Map are extension methods used for routing and mapping HTTP requests to
specific middleware, but they have distinct purposes and use cases:

MapGet Method:


MapGet is specifically designed to handle HTTP GET requests. It’s used to define endpoints that respond
only to GET requests.
 We typically use MapGet to retrieve data from the server without modifying its state, such as fetching a
list of items or getting details about a specific item.
 The MapGet method usually takes a route pattern and a request delegate (a handler function). The
handler function is executed when a GET request matches the specified route pattern.
Map Method:

 Map is a general method for handling all types of HTTP requests (such as GET, POST, PUT, DELETE, etc.).
It’s more flexible than MapGet.
 We need to use Map when we need to set up endpoints that might handle multiple types of HTTP
requests or when we have custom logic to determine the type of request to be handled.
 Similar to MapGet, Map also takes a route pattern and a request delegate. However, since Map can
handle various HTTP methods, the request delegate often contains logic to differentiate between these
methods.
Note: Once we progress in this course, we will discuss handling GET, POST, PUT, and DELETE requests using the
Map method.

How Do We Configure Middleware Components Using the Run() Extension Method?

Now, let us see how to configure Middleware Components using Run Extension. So, modify the Main method of
the Program class as follows to add a new custom Inline Middleware Component using the Run Extension
Method.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Initializes the configuration for the web application
var builder = WebApplication.CreateBuilder(args);
// Builds the web application based on the configured settings
var app = builder.Build();
//Configuring New Inline Middleware Component using Run Extension Method
app.Run(async (context) =>
{
await context.Response.WriteAsync("Getting Response from First Middleware");
});
// Starts the web application which begins listening for incoming requests
app.Run();
}
}
}
Now, run the application, and you should get the expected output, as shown in the image below.

If you go to the definition of the Run Extension Method, you will see the following signature. It basically adds a
terminal middleware delegate to the application’s request pipeline.

Here, you can see that it clearly says that this is an Extension Method used for adding terminal middleware
components. Terminal Middleware is the last middleware component.

You can also see from the above definition of the Run() Extension method that it takes an input parameter
of RequestDelegate. Now, if you go to the definition of RequestDelegate, then you will see the following.

As you can see in the above image, the RequestDelegate is a delegate that takes an input parameter of
type HttpContext object.

As we already discussed, the middleware components in an ASP.NET Core Web Application can access both HTTP
requests and responses because of the above HttpContext object. In our example, we are passing an anonymous
method or delegate to the Run Extension method and, moreover, passing the HTTP Context object as an input
parameter. The following diagram shows the above.
Instead of passing the request delegate inline as an anonymous method, we can define it in a separate method
and pass it here. For a better understanding, please modify the Program class code as follows.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Initializes the configuration for the web application
var builder = WebApplication.CreateBuilder(args);
// Builds the web application based on the configured settings
var app = builder.Build();
//Configuring New Inline Middleware Component using Run Extension Method
app.Run(FirstMiddleware);
// Starts the web application which begins listening for incoming requests
app.Run();
}
//This method signature must be the same as the RequestDelegate signature
private static async Task FirstMiddleware(HttpContext context)
{
//Using context object, we can access both Request and Response
await context.Response.WriteAsync("Getting Response from First Middleware");
}
}
}
In this example, the FirstMiddleware method is defined separately and then passed to the Run extension
method. Now, run the application, and you should see the same output.

Adding Multiple Middleware Components into the Request Processing Pipeline:

Let us modify the Program class as follows to add two custom inline middleware components to the Request
processing pipeline.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Initializes the configuration for the web application
var builder = WebApplication.CreateBuilder(args);
// Builds the web application based on the configured settings
var app = builder.Build();
//Configuring First Middleware Component using Run Extension Method
app.Run(async (context) =>
{
await context.Response.WriteAsync("Getting Response from First Middleware");
});
//Configuring Second Middleware Component using Run Extension Method
app.Run(async (context) =>
{
await context.Response.WriteAsync("Getting Response from Second Middleware");
});
// Starts the web application which begins listening for incoming requests
app.Run();
}
}
}
Now, we have two middleware components registered using the Run() extension method. Run the application,
and you will get the following output.

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

Then, the question that should come to your mind is how to call the next middleware component in the request
processing pipeline. The answer is to register the middleware component using the Use extension method.

Configuring Middleware Components Using the Use Extension Method

Let us modify the Program class code as follows to register the Middleware component using the Use extension
method. As you can see below, the First middleware component is registered using the Use extension method,
and the second middleware component is registered using the Run extension method.

As you can see in the code below, in the first Use Extension method, we pass two input parameters to the
anonymous method, i.e., context and next. Then, we call the next method, which will call the next middleware
component registered in the Request Processing Pipeline.
namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Initializes the configuration for the web application
var builder = WebApplication.CreateBuilder(args);
// Builds the web application based on the configured settings
var app = builder.Build();
//Configuring First Middleware Component using Use Extension Method
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Getting Response from First Middleware");
await next();
});
//Configuring Second Middleware Component using Run Extension Method
app.Run(async (context) =>
{
await context.Response.WriteAsync("\nGetting Response from Second Middleware");
});
// Starts the web application which begins listening for incoming requests
app.Run();
}
}
}
Now run the application, and you will see the output as expected, which is coming from both middleware
components, as shown in the image below.

Understanding the Use Extension Method in ASP.NET Core:

If you go to the definition of the Use extension method, you will see the following signature.
This method has also been implemented as an extension of 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 processing
pipeline.

Can we create a Terminal Middleware Component using the Extension method?

Yes, it is possible to create a terminal middleware component using the Use extension method in ASP.NET Core.
A terminal middleware component handles the request completely and does not call the next() delegate to pass
the request to the next middleware component. In this case, we need to specify the context object and request
delegate explicitly. For a better understanding, please modify the Program class as follows.

namespace FirstCoreWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Initializes the configuration for the web application
var builder = WebApplication.CreateBuilder(args);
// Builds the web application based on the configured settings
var app = builder.Build();
//Configuring First Middleware Component using Use Extension Method
//This will also act as a terminal Middleware Component
app.Use(async (HttpContext context, RequestDelegate next) =>
{
await context.Response.WriteAsync("Getting Response from First Middleware");
// Not calling 'next' since we want to terminate the pipeline here.
});
//Configuring Second Middleware Component using Run Extension Method
app.Run(async (context) =>
{
await context.Response.WriteAsync("\nGetting Response from Second Middleware");
});
// Starts the web application which begins listening for incoming requests
app.Run();
}
}
}
Differences Between Run, Map, and Use Extension Method in ASP.NET Core

In ASP.NET Core, Run, Map, and Use are extension methods for configuring the middleware pipeline. Each
method serves a distinct purpose in controlling the flow of HTTP requests in the request processing pipeline.
Understanding the differences between these extension methods is very important for effective pipeline
management and middleware configuration.

Run Extension Method:

 The Run extension method terminates the middleware pipeline. It does not accept the next parameter
because it is expected to be the final point in the middleware chain.
 The Run is used when no further processing should occur after the current middleware. Once a
middleware calls Run, no subsequent middleware is executed. It is typically used at the end of the
middleware pipeline.
Map Extension Method:

The Map extension method creates an endpoint routing middleware component. It allows us to specify
middleware that should only run for specific request paths.

It is useful for creating separate pipelines for different URL paths of the incoming request. This helps handle
different routes within the same application.

Use Extension Method:

 The Use extension method is the most flexible. It allows us to pass requests to the next middleware in
the pipeline. It takes a function that can do work before and/or after the next middleware.
 It is commonly used to add middleware that performs actions before calling the next middleware
component to process the request or to do additional processing after the next middleware has been
completed.
Note: If you use the Map and Run middleware, you will see that the Map endpoint might not write the output to
the Response stream.

You might also like