如何激活中间件

moh*_*adi 1 c# asp.net-core asp.net-core-middleware asp.net-core-webapi

我必须在其他地方激活它还是你可以帮助我?当我运行该项目时,它直接进入控制器并且中间件不运行。

这是我的中间件。

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)
        {
        
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

Yon*_*hun 5

对于 .NET Core、.NET 5 和 Startup.cs

确保您已Configure在 Startup 类的方法中注册了中间件。

public class Startup
{
    ...

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware<AuthenticationMiddleWare>();
    }
}
Run Code Online (Sandbox Code Playgroud)

参考: Configure方法-ASP.NET Core中的应用启动


对于没有 Startup.cs 的 .NET 6 及更高版本

  1. 为中间件编写一个扩展方法。
public static class MiddlewareExtensions
{
    public static IApplicationBuilder UseAuthenticationMiddleware(
        this IApplicationBuilder builder)
    {
        builder.UseMiddleware<AuthenticationMiddleWare>();
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. AuthenticationMiddleWare使用 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();
Run Code Online (Sandbox Code Playgroud)

参考: 编写自定义 ASP.NET Core 中间件