Middleware is software assembled into a pipeline to handle request and responses. Each component:
- Chooses if he passes the request to the next component.
- Can perform work before and after the next component.
Common use cases:
- Logging
- Authentication & Authorization
- Request/Response processing
- Caching
- Error handling
Implementation w. DI
We create our own custom middleware with an internal dependency, which is the class it’s going to process before/after our request.
// interface and its class, which do the processing
public interface IMiddlewareService
{
Task ProcessRequest(string request);
}
// interface implementation
public class MiddlewareService : IMiddlewareService
{
public async Task ProcessRequest(string request)
{
// do something with the request
Console.WriteLine(request);
}
}
Then we have our middleware class as such
public class CustomMiddleware(IMiddlewareService _service) : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
// custom logic to be executed BEFORE next middleware
await _service.ProcessRequest("middleware processing request");
await next(context);
// custom logic to be executed AFTER next middleware
}
}
Declaration inside Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// ... whatever
// register both: our custom middleware, and its internal dependency
services.AddTransient<IMiddlewareService, MiddlewareService>();
services.AddTransient<CustomMiddleware>();
// ... whatever else
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ... whatever
// declaration to use middleware
app.UseMiddleware<CustomMiddleware>();
// if we use this, the middleware declaration has to be BEFORE or else it won't work
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
})
// ... whatever else
}
Reference(s)
https://medium.com/@dushyanthak/best-practices-for-writing-custom-middlewares-in-asp-net-core-97b58c50cf9c
https://learn.microsoft.com/es-es/aspnet/core/fundamentals/middleware/write?view=aspnetcore-8.0
https://sardarmudassaralikhan.medium.com/custom-middleware-in-asp-net-core-web-api-70c2ffbbc095