Sunday, June 22, 2025

.NET Middleware

Inline
app.Use(async (context, next) =>
{
    var logger = app.Services.GetRequiredService<ILoggerFactory>()
        .CreateLogger("RequestLogger");

    logger.LogInformation("inline HTTP {Method} {Path}{Query}",
        context.Request.Method,
        context.Request.Path,
        context.Request.QueryString);
    
    await next();
});
Function
app.Use(MyFuncMiddleware);
async Task MyFuncMiddleware(HttpContext context, Func<Task> next)
{
    var logger = app.Services.GetRequiredService<ILoggerFactory>()
        .CreateLogger("RequestLogger");

    logger.LogInformation("func HTTP {Method} {Path}{Query}",
        context.Request.Method,
        context.Request.Path,
        context.Request.QueryString);
    
    await next();
}
HOC
app.Use(MyHocMiddleware());
Func<HttpContext, Func<Task>, Task> MyHocMiddleware()
{
     var logger = app.Services.GetRequiredService<ILoggerFactory>()
         .CreateLogger("RequestLogger");
     
    return async (context, next) =>
    {
        logger.LogInformation("hoc HTTP {Method} {Path}{Query}",
            context.Request.Method,
            context.Request.Path,
            context.Request.QueryString);
    
        await next();
    };
}
Fluent HOC
app.UseMyFluentHocMiddleware();

public static class MyFluentHocMiddlewareExtensions
{
    // Extension method for IApplicationBuilder to register our custom middleware
    public static IApplicationBuilder UseMyFluentHocMiddleware(this IApplicationBuilder builder)
    {
        var logger = builder.ApplicationServices.GetRequiredService<ILoggerFactory>()
          .CreateLogger("RequestLogger");
        
        return builder.Use(async (context, next) => 
        {
            logger.LogInformation("fluent HTTP {Method} {Path}{Query}",
                 context.Request.Method,
                 context.Request.Path,
                 context.Request.QueryString);

             await next();
        });
    }
}
Fluent Class
app.UseMyFluentClassMiddleware();

// Constructor: The RequestDelegate representing the next middleware MUST be the first parameter.
// Other dependencies (like ILogger) are injected by the DI container.

public class MyClassMiddleware(RequestDelegate next, ILogger<MyClassMiddleware> logger)
{
    // Invoke or InvokeAsync method: This is where the actual middleware logic resides.
    // It must return Task and take HttpContext as the first parameter.
    public async Task InvokeAsync(HttpContext context)
    {
        logger.LogInformation("myClass HTTP {Method} {Path}{Query}",
            context.Request.Method,
            context.Request.Path,
            context.Request.QueryString);
        
        await next(context);

        // logger.LogInformation($"[Class Middleware] Outgoing response status: {context.Response.StatusCode}");
    }
}

// Optional: An extension method to make registering the class middleware more fluent
public static class MyClassMiddlewareExtensions
{
    public static IApplicationBuilder UseMyFluentClassMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyClassMiddleware>();
    }
}

No comments:

Post a Comment