ASP.NET Core Middleware Pipeline Run(), Use() and Map() | .Net Core 3.1

In Asp.net core middleware is a delegate(run, use, and map) assembled into an application pipeline to handle requests and responses. middleware is a chain to pass the request to the next component or not and also perform work before and after the next component.

In this post, we will cover all that you need to know about ASP.NET Core Middleware and HTTP pipeline.

ASP  core has a few middleware that is readily available for use. This middleware is called built-in middleware. There are several built-in functions in ASP.NET core which are listed below:

MiddlewareDescription
AuthenticationUsed for authentication support.
CORSThis Configures Cross-Origin resource sharing.
RoutingThis adds routing capabilities  and implementing routing.
SessionThis adds support for managing user session.
StaticFileThis adds support for serving static files and directory browsing.

The HTTP request managed by request delegate that can be configured using three extension methods on the app builder class. let see how to use them and what differences they make.

Run Delegate

Run delegate receives only a context parameter it doesn’t know about the next middleware these delegates are usually called as terminal delegates because it terminates for ends the middleware pipeline.

Let’s consider an example where we taking a simple example to understand more about middleware. We set up the middleware in ASP.NET using the Configure method of our Startup class.

// This method gets called by the runtime.
        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.Run(async context =>
            {
                await context.Response.WriteAsync("Hello from 1st delegate.");
            });
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello from 2nd Middleware");
            });

        } 

The above example Middleware 1 will execute then after that it terminated the request and display the following text for each request.

asp.net core middleware

Use Delegate

Use: app.use()   it takes  http context  and the  delegate to the next middleware. In case we don’t use the next the it will behave exactly like run extension method. It will just execute the first middleware because we are not executing await next() so next middleware will never be execute. So it will act as terminal middleware. 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context,next) =>
            {
                await context.Response.WriteAsync("Hello from 1st delegate.");
                //await next();
            });
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello from 2nd Middleware");
            });
        } 

If we use await next() now what happen is after it executes  the first one it will execute  the next on also.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context,next) =>
            {
                await context.Response.WriteAsync("Hello from 1st delegate.");
                await next();
            });
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello from 2nd Middleware");
            });
        } 

Now you can see it executed the first one and then second on middleware  and  below text will be displayed.

Map Delegate

Map: Map as the name suggests. It basically maps to a path and creates a branch for the request pipeline which matches the path.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Hello from 1st delegate.");
                await next();
            });

            app.Map("/auth", a =>
            {
                a.Run(async (context) =>
                {
                    await context.Response.WriteAsync("New branch for auth");
                });
            });

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello from 2nd Middleware");
            });
        } 

Asp.net core middleware pipeline

In Asp.net core, Configuration is a method that sets up a middleware processing pipeline our ASP.net core application and sets the order of middleware execution in the request pipeline each middleware can perform operations before and after the next delegate.

The following diagram demonstrates the execution of asp.net core middleware components. The middleware execution follows the black arrows.

net core middleware | middleware pipeline

The code this method is generated by the empty project template this code sets up very simple request processing pipeline just two pieces of middleware were the first middleware Is this use developer exception page and the second middleware is registered using run extension method. Here we can do is write a message to the response object and the message will be displayed by the process.

  • Post category:.Net Core
  • Reading time:6 mins read