Introducing Middleware in ASP.NET
Middleware
2 Articles
In this article, let's learn about Middleware in ASP.NET.
Table of Contents
Introduction
In ASP.NET Core, the HTTP pipeline is built from middleware—components that see every request and response and decide how to act upon them, and whether to forward each one to the next component in the pipeline. Let's learn what middleware is and how to write middleware components of our own to enhance ASP.NET Core web applications.
What is middleware?
Middleware's are C# classes and logics connected by chain of responsibility pattern to handle and terminate request pipeline in the order of appearance. Middleware's are configured by default in Program.cs and the order in which they run are important. Request's are processed from top to bottom and outside to inside and back again. These are created once in application start up.
Each Middleware component can:
- Chooses whether to pass the request to the next component in the pipeline.
- Can perform work before and after the next component in the pipeline.
Middleware visualization
Request delegates are used to build the request pipeline. The request delegates handle each HTTP request. The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other. The following diagram demonstrates the concept. The thread of execution follows the violet arrows.
Each delegate can perform operations before and after the next delegate. Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline.
Summary
In this article, we learn't what is Middleware in ASP.NET and how it processes the request pipeline and how we can use middleware to customise the HTTP request. In next article let's learn about the types of middleware in ASP.NET.