Learn About Middleware In ASP.NET Core

Introduction

 
In this article, we are going to learn about middleware in ASP.NET Core.
 
Middleware is a very broad term. In asp.net core middleware is a piece of software that can handle an HTTP request or response. The middleware component has a very specific purpose and use. We can say that middleware is the heart of a .NET Core application.
 
Now let's learn more about middleware and how it works with an example.
 
Middleware is nothing but a class that is executed on every request in a .NET Core application.
 
For example, we may have a middleware component that authenticates a user, another middleware to handle errors yet another middleware that serves static files such as a Javascript file, CSS files, images, etc.
 
This is a middleware component that we use to set up a request processing pipeline that determines how a request is processed.
 
The request pipeline is configured as part of the application startup by the configure methods using the IApplicationBuilder instance that is present in startup class. As we already know, the execution of the .net core application starts from the main methods from where we call startup class.
 
The code of the middleware in the startup class is as follows, which is generated automatically when we create a project.
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  2.     if (env.IsDevelopment()) {  
  3.         app.UseDeveloperExceptionPage();  
  4.     }  
  5.     app.Run(async (context) => {  
  6.         await context.Response.WriteAsync("Hello World!");  
  7.     });  
  8. }  
In the above code, we can see two pieces of middleware. One is UseDeveloperExceptionPage and another one is setup using Run() methods which is generated by default when we create a new project using .NET Core.
 
Now let’s understand what middleware is and how it works. Consider the following diagram.

In the above diagram, we can see that middleware component has access to both incoming requests and the outgoing response. The middleware component first processes an incoming request and then executes the logics whatever code that will contain and then pass the request to the next middleware for further processing.
 
For example, in the above diagram, we have logging middleware which will simply log the time when the request is made and then pass the request to the next middleware which is static files. This will do its jobs and then pass the request to the next component, and so on.
 
The middleware component may handle the request and can decide not to call the next middleware component. This is called short-circuiting the request pipeline. A short circuit means we don’t want to execute the next middleware and want to back after certain middleware execution. The Run() method is used to terminate middleware so after this middleware, it cannot call the next middleware it would be the last middleware in a sequence.
 
For example, if the user makes the request for the static files only like image or CSS files, the StaticFiles middleware can handle the request and can serve the response as well. This means as per our diagram the StaticFiles middleware will not call the MVC middleware if the request is just only for StaticFiles.
 
We can configure multiple Middleware components in a .NET Core application which will be executed sequentially, like:
  1. Public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  2.     app.Run(async (context) => {  
  3.         await context.Response.WriteAsync("Hello from 1st Middleware");  
  4.     });  
  5.     app.Run(async (context) => {  
  6.         await context.Response.WriteAsync("Hello from 2nd Middleware");  
  7.     });  
  8. }  
We can see in the above example that we can add multiple middleware, but here we use the app.Run() extension methods, which will be the terminal of the request processing pipeline. After that, middleware terminates the execution. After that middleware, none of the other middleware will be executed. This means in the above code only the first middleware is executed, as we use the Run() method which will terminate the execution.
 
To configure multiple middlewares, we can use Use() extension methods which will use to add the next middleware in the request processing pipeline and executes the next middleware. Consider the following example:
  1. Public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  2.     App.Use(aync(context, next) => {  
  3.         await context.Response.WriteAsync(“Hello From First Middleware.”);  
  4.         await next();  
  5.     });  
  6.     App.Run(async (context) => {  
  7.         await context.Response.WriteAsync(“Hello From second Middleware”);  
  8.     });  
  9. }  
Output
 
Hello from First Middleware. Hello From second middleware
 
After running the application it will display a message like Hello from First Middleware Hello From second middleware.
 
In short, we can use Use() methods to add multiple middlewares in the request processing pipeline.
 
We can also use inbuilt middleware, listed below:
  1. Authentication - Adds authentication supports in .net core application.
  2. Routing - Add routing supports.
  3. StaticFiles - Add supports to serve static files.
  4. CORS - use to configure Cross-origin resource sharing.
  5. Session - Use to add session supports.

Summary

 
In this article, I shared my best knowledge about middleware in ASP.NET Core. I hope this will help you!