Skip to Content
Learn
Introduction To ASP.NET Middleware
Adding Custom Middleware Components

We know we can use IApplicationBuilder to add built-in middleware components to the request pipeline. We also know there’s an entire list of UseX() methods available via the interface. Although the built-in middleware provides a wide array of functionality, there may be times when we want to define our own middleware components. Remember when we talked about how middleware delegates perform their processing and then either call the next delegate in the sequence or short-circuit the pipeline? Let’s explore this concept as it relates to custom middleware components.

We are familiar with the UseX() methods provided by IApplicationBuilder. However, the interface also provides a generic Use() method which can be used to process custom middleware components and call the next component in the pipeline. Multiple middleware components can be chained together with the Use() method. The Use() method accepts two parameters, the HTTP context and the next middleware component to be called. Let’s take a look at each of these in more detail.

Previously, we discussed how performing actions inside of a web application correspond with sending requests, more specifically, HTTP requests. Well, each HTTP request and its specific data are encapsulated in the HTTP context object (of type HttpContext). So, when the HTTP context object is passed inside of the Use() method, we are just passing along the information about an individual HTTP request.

Each middleware component is responsible for making a decision. It must decide to either pass the request to the next component for processing or short-circuit the pipeline by returning a response. If the component is to pass the request to the next delegate in the sequence, the second parameter, next, is what provides for this functionality.

Instructions

1.

Click Run to view the bakery site.

2.

We’ve added a custom middleware component that writes A pass through the pipeline as the HTTP response. Uncomment the line of code in the app.Use() method which writes out the response and click Run to view the updated results.

Folder Icon

Sign up to start coding

Already have an account?