Curriculum
Custom Middleware Development in ASP.NET Core is an important skill for developers who need to implement application-specific request processing logic. While ASP.NET Core provides many built-in middleware components, there are situations where custom behavior is required, such as request logging, API key validation, performance monitoring, auditing, custom authentication, request filtering, and response modification.
Understanding Custom Middleware Development in ASP.NET Core helps developers build reusable, maintainable, and scalable solutions that integrate seamlessly into the ASP.NET Core request processing pipeline.
Custom Middleware is developer-created middleware that executes custom logic during request processing.
Example:
Request
↓
Custom Middleware
↓
Response
The middleware can inspect, modify, or terminate requests and responses.
Built-in middleware may not always satisfy business requirements.
Examples:
Custom Logging
API Key Validation
Request Tracking
Auditing
Performance Monitoring
Custom middleware solves application-specific problems.
Client
↓
Middleware
↓
Middleware
↓
Controller
↓
Response
Custom middleware becomes part of this pipeline.
E-Commerce Website:
Customer Request
↓
Custom Logging Middleware
↓
Authentication
↓
Product API
↓
Response
Every request can be logged automatically.
A middleware class typically contains:
Constructor
Invoke Method
Business Logic
These components work together to process requests.
Example:
public class
RequestLoggingMiddleware
{
}
This class will contain middleware logic.
Example:
private readonly
RequestDelegate next;
public
RequestLoggingMiddleware(
RequestDelegate next)
{
this.next = next;
}
The constructor receives the next middleware in the pipeline.
RequestDelegate represents:
Next Middleware
Purpose:
Continue Request Processing
It controls pipeline flow.
Every middleware requires:
public async Task
InvokeAsync(
HttpContext context)
{
}
This method processes requests.
HttpContext contains:
Request
Response
Headers
Cookies
User Information
It represents the current HTTP transaction.
public async Task
InvokeAsync(
HttpContext context)
{
Console.WriteLine(
"Request Started");
await next(context);
Console.WriteLine(
"Request Completed");
}
The middleware executes before and after the next component.
Request Started
↓
Controller
↓
Request Completed
The middleware surrounds endpoint execution.
Program.cs:
app.UseMiddleware<
RequestLoggingMiddleware>();
The middleware becomes part of the pipeline.
Example:
app.UseMiddleware<
RequestLoggingMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
Execution follows registration order.
Example:
var path =
context.Request.Path;
Purpose:
Capture Requested URL
Useful for monitoring.
Example:
var method =
context.Request.Method;
Results:
GET
POST
PUT
DELETE
Request information can be recorded.
Example:
var statusCode =
context.Response
.StatusCode;
Purpose:
Track API Responses
Useful for analytics and troubleshooting.
Example:
Console.WriteLine(
"Before");
await next(context);
Console.WriteLine(
"After");
Output:
Before
↓
Controller
↓
After
This demonstrates middleware flow.
Middleware can stop request processing.
Example:
await context.Response
.WriteAsync(
"Access Denied");
Result:
Pipeline Stops
Subsequent middleware does not execute.
Example Workflow:
Request
↓
Check API Key
↓
Valid?
↓
Continue
Or
Reject
Common in API security.
Example:
context.Response
.Headers.Add(
"App-Version",
"1.0");
Purpose:
Add Custom Response Headers
Useful for metadata.
Workflow:
Start Timer
↓
Execute Request
↓
Stop Timer
↓
Calculate Duration
Helps identify slow requests.
Example:
var stopwatch =
Stopwatch
.StartNew();
After execution:
stopwatch.Stop();
Request duration can be recorded.
Purpose:
Capture Errors
Log Exceptions
Improve Monitoring
Custom middleware often handles error tracking.
Example:
context.Request
.Query
Provides access to query string values.
Example:
context.Request
.Headers
Useful for authentication and auditing.
Example:
context.User
Provides authenticated user details.
Instead of:
app.UseMiddleware<
RequestLoggingMiddleware>();
Create an extension method.
Example:
public static class
MiddlewareExtensions
{
}
This improves readability.
public static
IApplicationBuilder
UseRequestLogging(
this IApplicationBuilder app)
{
return app
.UseMiddleware<
RequestLoggingMiddleware>();
}
Registration becomes cleaner.
Program.cs:
app.UseRequestLogging();
This is the preferred enterprise approach.
Middleware can use:
Logging Services
Repositories
Configuration
Database Services
ASP.NET Core injects dependencies automatically.
Example:
ILogger
Configuration
DbContext
Services enhance middleware capabilities.
Banking Application:
Middleware:
Audit Logging
Authentication
Fraud Detection
Authorization
Each component contributes to security.
Middleware:
Request Tracking
Role Validation
Patient Access Monitoring
Sensitive operations are monitored.
Middleware:
Cart Tracking
Analytics
Authentication
Order Validation
Custom middleware supports business requirements.
Middleware can be reused across projects.
Logic remains centralized.
Supports large applications.
Keeps responsibilities isolated.
Supports custom business requirements.
These benefits make custom middleware extremely powerful.
May stop pipeline execution unexpectedly.
Can reduce performance.
May create functionality issues.
Creates security risks.
Increases maintenance effort.
Custom Middleware is developer-created middleware that processes requests and responses.
RequestDelegate represents the next middleware in the pipeline.
HttpContext contains request and response information.
It forwards requests to the next middleware component.
Stopping pipeline execution before reaching subsequent middleware.
It enables implementation of application-specific request processing logic.
Custom Middleware is a developer-created component that processes HTTP requests and responses.
RequestDelegate represents the next middleware in the request pipeline.
HttpContext contains all information related to the current HTTP request and response.
The middleware pipeline stops and subsequent middleware does not execute.
Custom middleware allows developers to implement custom business logic, logging, security, monitoring, and request processing features.
It provides flexibility, reusability, maintainability, and support for custom application requirements.
WhatsApp us