Writing a Minimal Custom Middleware in ASP.NET Core
ASP.NET Core’s request pipeline is a powerful concept built entirely around middleware. Think of it as an assembly line for your HTTP requests. Each station on the line is a piece of middleware that can inspect, modify, or act upon the request before passing it to the next station.
While ASP.NET Core provides a rich set of built-in middleware for things like routing, authentication, and static files, there will inevitably come a time when you need to create your own. Whether it’s for custom logging, header manipulation, or a unique authentication scheme, writing custom middleware is a fundamental skill.
In this guide, we’ll break down the process into its simplest form, showing you two minimal ways to create and use your own middleware.
Approach 1: The Convention-Based Class
The most common and structured way to create middleware is by defining a class that follows a specific convention. This approach is clean, reusable, and testable.
A middleware class needs two things:
- A constructor that accepts a
RequestDelegateparameter. This delegate represents the next piece of middleware in the pipeline. - A public method named
InvokeAsync(orInvoke) that accepts anHttpContextas its first parameter. This is the method that gets executed.
Let’s create a simple middleware that logs the incoming request path and the outgoing response status code.
Step 1: Create the Middleware Class
Create a new file named SimpleLoggingMiddleware.cs. We’ll use a primary …