在EndpointRoutingMiddleware和EndpointMiddleware之间调用管道的Map()for



https://source.dot.net/#Microsoft.AspNetCore.Routing/Builder/EndpointRoutingApplicationBuilderExtensions.cs,150

我正在阅读EndpointRoutingApplicationBuilderExtensions的源代码,它有以下方法:

private static void VerifyEndpointRoutingMiddlewareIsRegistered(IApplicationBuilder app, out IEndpointRouteBuilder endpointRouteBuilder) {
if (!app.Properties.TryGetValue(EndpointRouteBuilder, out var obj)) {  // I can understand this part
var message = "...";
throw new InvalidOperationException(message);
}

endpointRouteBuilder = (IEndpointRouteBuilder)obj!;
// This check handles the case where Map or something else that forks the pipeline is called between the two routing middleware 
if (endpointRouteBuilder is DefaultEndpointRouteBuilder defaultRouteBuilder && !object.ReferenceEquals(app, defaultRouteBuilder.ApplicationBuilder)) {
var message = $"The {nameof(EndpointRoutingMiddleware)} and {nameof(EndpointMiddleware)} must be added to the same {nameof(IApplicationBuilder)} instance. " +
$"To use Endpoint Routing with 'Map(...)', make sure to call '{nameof(IApplicationBuilder)}.{nameof(UseRouting)}' before " +
$"'{nameof(IApplicationBuilder)}.{nameof(UseEndpoints)}' for each branch of the middleware pipeline.";
throw new InvalidOperationException(message);
}
}

我不理解第二部分,这是否意味着Map(...)UseRouting()UseEndpoints()之前被调用为:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseRouting();

app.Map("/branch", app => {
await context.Response.WriteAsync("branch detected");
});

app.UseEndpoints(endpoints => {
endpoints.MapGet("routing", async context => {
await context.Response.WriteAsync("Request Was Routed");
});
});

app.Use(async (context, next) => {
await context.Response.WriteAsync("Terminal Middleware Reached");
await next();
});
}

我看不出上面的代码有任何错误,那么源代码是什么意思,我如何才能重现该方法显示的错误?

下面的例子练习了您强调的代码:

public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.Map("/branch", branchApp =>
{
branchApp.UseEndpoints(endpoints =>
{
// ...
});
});
app.UseEndpoints(endpoints =>
{
// ...
});
}

正如错误消息所示,这是为了确保中间件管道的每个分支都有一对匹配的UseRoutingUseEndpoints。在我展示的示例中,缺少对branchApp.UseRouting()的调用,因此这会触发错误。

最新更新