Create a custom middleware pipeline using .NET Core

Photo by Fabian Grohs on Unsplash

What is middleware?

Configuring the HTTP pipeline

public void Configure(IApplicationBuilder app)
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
}

Create custom middleware

public class CustomLoggerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public CustomLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<CustomLoggerMiddleware>();
}
public async Task Invoke(HttpContext context)
{
_logger.LogInformation("**Handling request: " + context.Request.Path + "**");
await _next.Invoke(context);
_logger.LogInformation("**Finished handling request.**");
}
}
public static class CustomLoggerExtension
{
public static IApplicationBuilder UseCustomLogger(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomLoggerMiddleware>();
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseCustomLogger();
}
You should see a similar output from the ASP.NET Core Web Server after starting the web application