Theme-Logo
  •   .Net
    •   C Sharp(C#)
    •   Web API
    •   Micro Services
    •   ASP.Net
    • ASP.Net MVC
    • .Net Core
  •   Database
    • SQL Server
    • Oracle
    • PostgreSQL
  •   jQuery
    • jQuery Tutorials
    • jQuery Plugins
    • jQuery UI
    • More on jquery
  •   Tutorials
    • Microservices Tutorials
    • DotNet Core Tutorials
    • PostgreSql Tutorials

Middleware and Request delegate in dot net core

Understand Middleware

A middleware is nothing but a component or class which is executed on every request in ASP.NET Core application something like HttpHandlers and HttpModules were part of request pipeline in Asp.Net. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed in each request.

So, 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. We can also make a class (middleware) to handle authentication and authorization in entire application.

Typically, there will be multiple middleware in ASP.NET Core web application. It can be either framework provided middleware, added via NuGet or your own custom middleware.

Understanding Configuration Of Middleware

We can configure middleware in the Configure method of the Startup class using IApplicationBuilder instance. The following example adds a single middleware using Run method which returns a string "DotNet Palace!!" on each request.

                                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("DotNet Palace!!");              
                                        });

                                    ......
                                    ......
                                    }
                                }
                        

In the above example, Run() is an extension method on IApplicationBuilder instance which adds a terminal middleware to the application's request pipeline. The above configured middleware returns a response with a string "DotNet Palace!!" for each request.

Understand Run Method

The Run method is an extension method on IApplicationBuilder and accepts a parameter of RequestDelegate. We use Run method to add middleware. Below is signature of Run method-

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

The RequestDelegate is a delegate method which handles the request. The following is a RequestDelegate signature.

                                public delegate Task RequestDelegate(HttpContext context);
                        

The Run method accepts a method as a parameter whose signature should match with RequestDelegate. Therefore, the method should accept the HttpContext parameter and return Task.

How To Configure Multiple Middleware

Mostly there will be multiple middleware components in ASP.NET Core application which will be executed sequentially. The Run method adds a terminal middleware so it cannot call next middleware as it would be the last middleware in a sequence. The following will always execute the first Run method and will never reach 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"); 
                                    });
                                }
                        

To configure multiple middleware, use Use() extension method. It is similar to Run() method except that it includes next parameter to invoke next middleware in the sequence. Consider the following example.

                                public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                                {
                                    app.Use(async (context, next) =>
                                    {
                                        await context.Response.WriteAsync("Hello World From 1st Middleware!");

                                        await next();
                                    });

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

Thus, we can use Use() method to configure multiple middlewares in the order we like.

Trending Post
Benefits of using ASP.NET Core over ASP.NET.
Role of Startup class in .Net Core.
Interview Questions and Answers
What is Request delegate?
What is Host in ASP.NET Core?
Describe the Generic Host and Web Host?
Describe the Servers in ASP.NET Core?
How to read values from Appsettings.json file?
How to handle errors in ASP.NET Core?
About us

DotNet Palace is a community platform created and maintained by The articles are mainly focused on Microsoft stack technologies like C#, ASP.Net, MVC, .Net Core, SQL Server and Oracle, PostgreSQL, SQLite etc. To improve the site's content you can send your valuable suggestions at info.dotnetpalace@gmail.com

Quick links
  • SOLID Principles
  • Questions
  • OOPS Principles
  • DotNet Palace Tutorials
  • Privacy Policy
  • Terms and Condition