We've seen in the previous section how we can write custom attributes to perform actions before and after a controller action, and, in Chapter 1, Getting Started with ASP.NET Core, how we can write middleware. Now, a simple middleware class to log all requests can be written as follows:
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILoggerFactory _loggerFactory;
public LoggingMiddleware(RequestDelegate next, ILoggerFactory
loggerFactory)
{
this._next = next;
this._loggerFactory = loggerFactory;
}
public async Task InvokeAsync(HttpContext context)
{
var logger = this._loggerFactory.CreateLogger<LoggingMiddleware>
();
using (logger.BeginScope<LoggingMiddleware>(this))
{
logger.LogInformation("Before request");
await this._next.Invoke(context);
logger.LogInformation("...