Middleware in ASP.NET Core is software that's assembled into the application pipeline to handle requests and responses. ASP.NET Core gives developers full control over how requests are processed.
Inline Middleware
- Inline middleware is written directly in the Program.cs file using app.Use(...)
- It uses a lambda function to handle the request and response logic
- Middleware code runs in order as it appears in the pipeline
- Doesn’t support dependency injection (can't use services directly)
- Supports writing async logic using async/await
- Best for quick tasks, testing, or temporary conditions
Convention-Based Middleware
- Convention-based middleware is written as a separate class
- Used for reusable and clean middleware logic
- Keeps the main pipeline (Program.cs) short and organized
- Created in a separate class with Invoke or InvokeAsync method
- Registered using app.UseMiddleware<YourMiddleware()
Factory-Based Middleware
- Created like convention-based middleware, but uses IMiddleware interface
- The class implements IMiddleware and defines Task InvokeAsync(HttpContext context, RequestDelegate next)
- Middleware instance is created by the DI container (not reused like convention-based)
- Best when the middleware needs scoped services (like DbContext) or per-request behavior
Conclusion
Middleware is the backbone of request processing in ASP.NET Core. By understanding and leveraging built-in, custom, and inline middleware, you can gain full control over how your application handles HTTP requests and responses. Whether you're implementing logging, authentication, or custom request handling logic, mastering middleware is key to building scalable and maintainable web applications.