Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to activate middleware

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)
        {
        
        }
    }    
}
like image 750
mohammad asadi Avatar asked Feb 26 '26 19:02

mohammad asadi


1 Answers

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

  1. Write an extension method for middleware.
public static class MiddlewareExtensions
{
    public static IApplicationBuilder UseAuthenticationMiddleware(
        this IApplicationBuilder builder)
    {
        builder.UseMiddleware<AuthenticationMiddleWare>();
    }
}
  1. Register 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

like image 105
Yong Shun Avatar answered Feb 28 '26 08:02

Yong Shun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!