Creating custom middleware in .NET is straightforward and powerful. Here's a quick step-by-step guide to help you build and register your own middleware.
First, create a folder named Middlewares
to store all your custom middleware classes. Inside this folder, create a middleware called RequestIPMiddleware
which is encapsulated in a class. This middleware logs the user's IP address to the console.
Here's an example.
public class RequestIPMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public RequestIPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<RequestIPMiddleware>();
}
public async Task Invoke(HttpContext context)
{
_logger.LogInformation($"User IP: {context.Connection.RemoteIpAddress}");
await _next.Invoke(context);
}
}
Second, create an Extensions
folder to store your middleware extension methods. Inside it, add a new static class called RequestIPExtension
. This extension method allows you to easily register the middleware in your application.
public static class RequestIPExtension
{
public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestIPMiddleware>();
}
}
Third, open your Program.cs
file and register the custom middleware, which is exposed via an extension method, like this:
var app = builder.Build();
// your custom middleware
app.UseRequestIP();
app.UseStaticFiles();
Run your application, and you should see the user's IP address logged in the console.
If your middleware is simple and you don't want to create a separate class or extension method, you can also define an inline middleware directly in Program.cs
, like this:
app.Use(async (context, next) =>
{
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("RequestIPLogger");
logger.LogInformation($"User IP: {context.Connection.RemoteIpAddress}");
await next(context);
});
Easy, right? Job done☑️
Thanks for reading!
If you like this article, please don't hesitate to click the heart button ❤️
or follow my GitHub I'd appreciate it.
Top comments (0)