An Overview of Middleware in ASP.Net Core
Tags: aspdotnet, dotnetcore, webdev, beginners
Published: 2023-06-13 06:58:21

Middleware was initially proposed in ASP.NET Core 1.0. A middleware is nothing but a component that is implemented on every request in the ASP.NET Core application. In the superior ASP.NET, HttpHandlers and HttpModules were a segment of the request pipeline.

Middleware is equivalent to HttpHandlers and HttpModules where both require to be built and accomplished in each request. It can also rule that how any application looks when there is an error, and it is a vital piece in how we validate and legalize a user to perform certain actions.

- Every single piece of middleware in .NET Core is an object, and it has a very distinct, fascinated, and finite role.
- Each component selects whether to pass the request on to another component in the pipeline and can conduct certain steps before and after it is supplicated in the pipeline.
- Request delegates are used to create the request pipeline and they handle each HTTP request.
- Middleware are software components that are manufactured into an application pipeline to manage requests and responses.
- Eventually, we need many segments of middleware for an application to behave accordingly.


Number of [Asp.Net Core development firms](https://www.ifourtechnolab.com/hire-dot-net-core-developer) rely on .Net Core projects that are built with incorporating multiple Middleware that handles request-response pipeline. The updated features inside Asp.Net Core make it more attractive and empower the application’s performance.

## How does it work?

Middleware was initially proposed in ASP.NET Core 1.0. A middleware is n*othing but a component that is implemented on every request in the ASP.NET Core application. In the superior ASP.NET, HttpHandlers and HttpModules were a segment of the request pipeline.

In returned response travels back in the obverse direction back through the pipeline which encourages each component to run code both times, when the request enters and also when the response is on its way out.

#### Read More: [.Net Core By Microsoft - New Step Towards Cross-platform Software Development](https://www.ifourtechnolab.com/blog/net-core-by-microsoft-new-step-towards-cross-platform-software-development)

## Configure Middleware with IApplicationBuilder
Let’s configure middleware in the Configure method of the Startup class manipulating the IApplicationBuilder instance. The subsequent example appends a single middleware by using the Run method which returns a string "Hello World!" on individual requests.

```
public class Startup
{
    public Startup()
    {
    } 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //configure middleware using IApplicationBuilder here..
            
        app.Run(async (context) =>
        {              
            await context.Response.WriteAsync("Hello World!");
              
        });

        // other code removed for clarity.. 
    }
}

```

As per the above case, Run () is a supplement method on the IApplicationBuilder instance that joins a terminal middleware to the application's request pipeline. The above-configured middleware replaces a response with a string "Hello World!" for an individual request.

## Run, Use, and Map Method

app.Run()

- This portion of middleware can expose Run[Middleware] methods which are executed at the end of the pipeline. This typically serves as a middleware terminal and is inserted at the end of the request queue, as it can not call the next middleware
- To add middleware, we used the Run extension process. The Run process signature is as follows:

```
public static void Run(this IApplicationBuilder app, RequestDelegate handler)

```

- The Run method on IApplicationBuilder is an extension method and accepts a RequestDelegate parameter. The RequestDelegate is a form for delegates who manage the request. The following is a Signature of the RequestDelegate.

```
public delegate Task RequestDelegate(HttpContext context);
```

app.Use()

- This is for multiple middleware configuration. Unlike app. Run(), we can include in it the next parameter which calls in the pipeline the next request delegate. We can also get the pipeline short circuit (end) by not calling the next parameter.

app.Map()

- These extensions are used as a standard for pipeline branching. The map branches the request pipeline based on matches of the request route in question. When the request path begins with the specified path the branch will be executed.


## Configure multiple Middleware

In most cases, there will be multiple middleware components in the ASP.NET Core application which will be implemented consecutively. The Run method adjoins a terminal middleware so it cannot call another middleware as it would be the last middleware in an order.

The following will always implement the first Run method and will never outreach the second Run method.

```
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World From 1st Middleware"); 
    });
    
    // the following will never be executed
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World From 2nd Middleware"); 
    });
}

```

Make use of Use() extension method to configure multiple middlewares. It is the same as the Run() method except that it comprises other limitations to solicit the next middleware in the sequence.

## Add Built-in Middleware Via NuGet
ASP.NET Core is an extensible framework. If needed, we can include server-side features in our application by installing various plug-ins via NuGet. Many middleware plug-ins are available nowadays which we can be utilized in our application.

Look at some built-in middleware:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i272xqfjx8rytwxy22te.png)

#### Looking to [Hire ASP.Net Developer](https://www.ifourtechnolab.com/hire-dot-net-developer)? Contact Now


## Custom Middleware
On NuGet, we can use some custom middleware. For example: Middleware Diagnostics.

Diagnostics middleware is used in ASP.NET Core to record and manage exceptions and defects, and to diagnose Entity System Migration Defects.

This package comprises these middleware and extension methods.

- DeveloperExceptionPageMiddleware — UseDeveloperExceptionPage():
It generates HTML error responses by capturing synchronous and asynchronous exceptions from the pipeline.
- ExceptionHandlerMiddleware — UseExceptionHandler(): 
Catch exceptions, log them and re-execute in an alternate pipeline.
- StatusCodePagesMiddleware — UseStatusCodePages(): 
Check for responses with status codes between 400 and 599.
- WelcomePageMiddleware — UseWelcomePage(): 
Display Welcome page for the root path

## Summary

- Will be executed in the order attached to the pipeline.
- Can terminate the request pipeline (short-circuit) where necessary.
- Can simply move the request on in the pipeline to the next piece of middleware. perform some processing logic, and then pass the request for further processing to the next middleware.
- Has access both to incoming requests and to outgoing responses.