Middleware: What is it?
A middleware is a little piece of software that handles HTTP requests and responses in ASP.NET Core.
Every middleware operates in a pipeline and is capable of:
- Execute a task prior to the subsequent middleware execution.
- After it runs, take a certain action, or
- even prevent the request from being processed further.
To put it simply, middleware can examine, alter, or end a request or response, much like a checkpoint in the request pipeline.
ASP.NET Core comes with built-in middleware such as:
UseRouting()— Handles URL routingUseAuthentication()— Handles login/authUseAuthorization()— Manages access controlUseStaticFiles()— Serves static files like images or CSS
You can also create your own custom middleware to add specific logic (like logging, validation, or tracking).
Let’s create a simple custom middleware that logs each incoming request and outgoing response.
It’s good practice to add an extension method so you can easily use your middleware.
Program.csIn .NET 6+, middleware is added in the request pipeline using the app object.
Step 4. Run and Test
Now run your application (Ctrl + F5).
When you send a request (like GET /api/values), you’ll see logs in the console:
Your custom middleware successfully intercepted and logged the request and response!
When a request comes in:
The first middleware receives it.
It can do something (like logging) and call the next middleware.
The request flows through all middleware components.
The response flows back through them in reverse order.
Custom middleware is useful for:
Logging requests and responses
Handling exceptions globally
Adding custom headers or tokens
Measuring performance
Implementing request filters (e.g., IP blocking)
Here’s another short example that adds a custom header to all responses:
Register it in Program.cs:
Every response from your app will now include:
Summary
| Step | Action |
|---|---|
| 1 | Create a middleware class with InvokeAsync(HttpContext) |
| 2 | Add an extension method for better reusability |
| 3 | Register it in the request pipeline using the app.UseMyCustomMiddleware() |
| 4 | Test by sending a request and checking the console or response headers |
Conclusion
Custom middleware gives you complete control over the request and response pipeline in ASP.NET Core.
It helps you write clean, reusable, and centralized logic for logging, authentication, or any pre/post-processing.
In short: Middleware is the heart of ASP.NET Core request handling — and custom middleware lets you extend that heart for your unique business needs.


0 comments:
Post a Comment