在使用 MapWhen 分支到 运行 时注册中间件,它仅用于一组端点

Registering a middleware while using MapWhen for branching to run it just for a set of endpoints

我需要 运行 两个中间件用于我的所有端点,但 /accounts/* 下的端点除外。

我在 ConfigureServices 中使用这个:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddControllers();
}

配置方法如下所示:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IUserService  userService)
{
    app.UseCors(builder => builder
        //.AllowAnyOrigin()
        .SetIsOriginAllowed((host) => true)
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());

    app.UseRouting();

    app.UseAuthentication();

    //THIS IS WHAT I JUST ADDED TO SUPPORT THE BRANCHING OF ROUTES
    app.MapWhen(context =>
    {
        return !context.Request.Path.StartsWithSegments("/accounts");
    }, appBuilder =>
    {
        appBuilder.UseMiddleware<TenantProviderMiddleware>();
        appBuilder.UseMiddleware<UserClaimsBuilderMiddleware>();
    });

    //app.UseMiddleware<TenantProviderMiddleware>();
    //app.UseMiddleware<UserClaimsBuilderMiddleware>();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<VehicleHub>("/vehicle-hub");
        endpoints.MapControllers();
    });

 }

但我收到以下错误:

System.InvalidOperationException: The request reached the end of the pipeline without executing the endpoint: 'WebAPI.Controllers.VehiclesController.Get (WebApi)'. Please register the EndpointMiddleware using 'IApplicationBuilder.UseEndpoints(...)' if using routing.

根据错误,我了解到我应该在 MapWhen 方法中使用 UseEndpoints 而不是 UseMiddleware,但无法正确使用。

那中间件应该怎么注册呢?

看来你需要UseWhen, which, according to the docs:

...branches the request pipeline based on the result of the given predicate. Unlike with MapWhen, this branch is rejoined to the main pipeline if it doesn't short-circuit or contain a terminal middleware

因为您使用的是 MapWhenUseAuthorizationUseEndpoints 都不会影响您的 /accounts/ 路径。您显示的错误是因为 Endpoints 中间件在这种情况下没有 运行。