我需要为所有端点运行两个中间件,但 /accounts/* 下的端点除外。
我在配置服务中使用它:
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:请求到达管道末尾,但未执行端点:“WebAPI.Controllers.VehiclesController.Get (WebApi)”。如果使用路由,请使用“IApplicationBuilder.UseEndpoints(...)”注册 EndpointMiddleware。
从错误中我了解到我应该在 MapWhen 方法中使用 UseEndpoints 而不是 UseMiddleware,但无法正确执行。
那我应该如何注册中间件呢?
看起来你需要UseWhen https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.usewhenextensions.usewhen?view=aspnetcore-3.1,其中,根据docs https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1#branch-the-middleware-pipeline:
...根据给定谓词的结果分支请求管道。不同于与MapWhen
,如果该分支没有短路或包含终端中间件,则它会重新加入主管道
因为你正在使用MapWhen
, both UseAuthorization
and UseEndpoints
对你没有影响/accounts/
路径。您显示的错误是因为 Endpoints 中间件在这种情况下不运行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)