在使用MapWhen进行分支时注册中间件以仅针对一组端点运行该中间件 [英] Registering a middleware while using MapWhen for branching to run it just for a set of endpoints
问题描述
我需要为所有端点(/accounts/*下的端点)运行两个中间件.
I need to run two middlewares for all my endpoints but the ones under /accounts/*.
我在ConfigureServices中使用它:
I use this in 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();
});
}
但是我遇到了以下错误:
But I'm getting the following error:
System.InvalidOperationException:请求到达了管道的末尾,而没有执行端点:"WebAPI.Controllers.VehiclesController.Get(WebApi)".如果使用路由,请使用"IApplicationBuilder.UseEndpoints(...)"注册EndpointMiddleware.
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,但无法正确处理.
From the error I understand that I should be using UseEndpoints instead of UseMiddleware in the MapWhen method but can't get it right.
那我该如何注册中间件?
How should I register the middlewares then?
推荐答案
您似乎需要文档:
...根据给定谓词的结果分支请求管道.与
MapWhen
不同,如果该分支没有短路或包含终端中间件,则该分支将重新连接到主管道
...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
因为您使用的是 MapWhen
,所以 UseAuthorization
和 UseEndpoints
都不会影响您的/accounts/
路径.您显示的错误是因为在这种情况下Endpoints中间件未运行.
Because you're using MapWhen
, both UseAuthorization
and UseEndpoints
have no affect for your /accounts/
paths. The error you've shown is because the Endpoints middleware isn't running in this scenario.
这篇关于在使用MapWhen进行分支时注册中间件以仅针对一组端点运行该中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!