| by Achyut Kendre | No comments

What is Middleware in ASP.NET Core?

ASP.NEt Core Middleware
ASP.NET Core Middleware

Example Link https://drive.google.com/file/d/1oJHRNj5fKTXUg6qgjIjPdhv4zkekhkbn/view?usp=sharing

A Middleware is nothing but a component (class) which is executed on every request. Middleware is a software component that are assembled into an application request pipeline, before going in detail we will try to understand the startup class in details.

Main Method in ASP.Net Core?

  • Initially ASP.NET Core application stars as console application.
  • Main method is entry point for application.
  • Where we can configure ,host and run asp.net core application
  • CreateWebHostBuilder calls createDefaultBuilder method of WebHost it creates default web host with certain preconfigured default settings.
  • It Uses a Startup class, which contains methods to configure services and Configure.

Create Default Builder Method in ASP.NET Core

This method will do the following activities –

  • Setting up the web server.
  • Loading the host and application configuration from various configuration sources.
  • Configuration logging.
  • It Uses a Startup class, which contains methods to configure services and Configure

What is Startup Class in ASP.Net Core?

ASP.NET Core application must include Startup class. It is like Global.asax in the traditional .NET application. As the name suggests, it is executed first when the application starts.
The startup class can be configured using UseStartup() method at the time of configuring the host in the Main() method of Program class.

The startup class can be configured using UseStartup() method at the time of configuring the host in the Main() method of Program class. The name “Startup” is by ASP.NET Core convention. However, we can give any name to the Startup class, just specify it as the generic parameter in the UseStartup() method.

The Startup class must include a Configure method and ConfigureService method.

ConfigureServices() Method in ASP.Net Core

  • Dependency injections are built in in ASP.NET Core (built in IOC Container).
  • The ConfigureServices method is a place where you can register your dependent classes with the built-in IoC container.
  • Once Registered dependent class, it can be used anywhere in the application.
  • Include it in the parameter of the constructor of a class where you want to use it. (Cosntructor injection).
  • The IoC container will inject it automatically.
  • ASP.NET Core refers dependent class as a Service.
  • So, whenever you read “Service” then understand it as a class.
  • ConfigureServices method includes IServiceCollection parameter to register services to the IoC container.

Configure() Method in ASP.NET Core

  • The Configure method is a place where you can configure application request pipeline.
  • It uses IApplicationBuilder instance that is provided by the built-in IoC container.
  • Here we can tell the ioc to inject the middle wares in request pipe line.
  • We can inject only those middleware’s those required by application will improve the performance of application.

Middleware in ASP.NET Core

ASP.NET Core has a new concept -Middleware. A middleware is nothing but a component (class) which is executed on every request. Middleware is a software component that are assembled into an application request pipeline. Every middle ware has a specific purpose or role in request pipe line. Like authenticate users, logging errors, server static files. Middleware’s can be built in provided by Framework or can be custom (user defined).

You can Set the order of middleware execution in the request pipeline. Each middleware adds or modifies http request and optionally passes control to the next middleware component. Configure middleware in the Configure method of the Startup class using IApplicationBuilder instance.
IApplicationBuilder provides run and use method to create middleware.

Pictorially it will be as follows –

Middlwares can be built in or user defined (Custom) to create the middlware we can use the IApplicationBuilder Provides you two methods Run and Use as follows –

Create Middleware using Run Method in ASP.NET Core

  • The Run method is an extension method on IApplicationBuilder & accepts a parameter of HttpContext.
  • The RequestDelegate is a delegate method which handles the request.
  • The Run method is an extension method on IApplicationBuilder and accepts a parameter of RequestDelegate.
  • Run method has limitation that it will short circuit the Reqeust Pipe Line.

You can use the lambda function syntax or you can also create separate method as a Middleware.

Using Lambda Function Syntax

app.Run(async(context)=>{
 await context.Response.WriteAsync("Hello World!"); }); 

Separate Function Syntax

Public void Configure(IApplicationBuilder app, 
IHostingEnvironment env) { 
app.Run(MyMiddleware); 
} 

private Task MyMiddleware(HttpContext context){ 
return context.Response.WriteAsync("Hello World! "); 
} 

Create Middlware using Use Method in ASP.Net Core.

  • Use method is used to configure multiple middleware.
  • Use() method has 2 parameters. The first parameter is the HttpContext & second parameter is the Func type(generic delegate) that represents next middleware in the pipeline.

It Means use method has a next delete which contains the reference of next middleware in request pipe line to which request will be given.

app.Use(async (context, next) => {
await context.Response.WriteAsync("Hello World From 1st Middleware!"); 
await next(); });

How middleware works in ASP.NET Core?

  • Has Access to both Request & Response
  • May simply pass the Request to next Middleware
  • May process and then pass the Request to next Middleware
  • May handle the request and short circuit the pipeline
  • May Process the outgoing Response.
  • Middleware’s are executed in the order they area added.

You can understand it pictorially as follows –

Middleware Example using ASP.NET Core 3.1

Step 1: create a empty asp.net core project using vs code edit.

Step 2: Create following middleware’s in Configuremethod and use ILogger service to log the output of the middlware in output window of Startup class as follows –

public void Configure(IApplicationBuilder app, IWebHostEnvironment env,ILogger<Startup> log)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //first middlware
            app.Use(
                 async (cnt,next)=> {
                     log.LogInformation("Request inside first middlware!");
                     await next();
                     log.LogInformation("Response from first middleware");
                   }
                );
            app.Use(
                 async (cnt, next) =>
                 {
                     log.LogInformation("Request inside second middlware!");
                     await next();
                     log.LogInformation("Response From second Middleware!");

                 }
                );
            app.Run(
                 async(cnt) => {
                     log.LogInformation("Request inside third middlware!");
                     log.LogInformation("Response From Third middlware!");
                 }
                );
        }

Step 3: Run the program and look at the output window, you will find a log and it is exactly similar to the image or diagram.