Do I have to activate it elsewhere or can you help me? When I run the project, it goes straight to the controller and middleware does not run.
This is my middleware.
public class AuthenticationMiddleWare
{
private RequestDelegate nextDelegate;
public AuthenticationMiddleWare(RequestDelegate next, IConfiguration config)
{
nextDelegate = next;
}
public async Task Invoke(HttpContext httpContext)
{
try
{
// somecode
await nextDelegate.Invoke(httpContext);
}
catch (Exception ex)
{
}
}
}
For .NET Core, .NET 5 with Startup.cs
Make sure you have registered your middleware in Configure method in Startup class.
public class Startup
{
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<AuthenticationMiddleWare>();
}
}
Reference: The Configure method - App startup in ASP.NET Core
For .NET 6 and above without Startup.cs
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseAuthenticationMiddleware(
this IApplicationBuilder builder)
{
builder.UseMiddleware<AuthenticationMiddleWare>();
}
}
AuthenticationMiddleWare with the extension method in Program.cs./* Import namespace of MiddlewareExtensions.cs */
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
...
app.UseAuthenticationMiddleware(); // Register middleware, order of sequence matter
...
app.Run();
Reference: Write custom ASP.NET Core middleware
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With