【发布时间】:2022-01-17 10:55:54
【问题描述】:
我正在阅读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();
});
}
我看不出上面的代码有什么问题,那么源代码是什么意思,如何重现该方法显示的错误?
【问题讨论】:
标签: c# asp.net-core routes