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();
});
}
我看不出上面的代碼有什么問題,那么源代碼是什么意思,我怎樣才能重現該方法顯示的錯誤?
uj5u.com熱心網友回復:
以下示例練習了您突出顯示的代碼:
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.Map("/branch", branchApp =>
{
branchApp.UseEndpoints(endpoints =>
{
// ...
});
});
app.UseEndpoints(endpoints =>
{
// ...
});
}
正如錯誤訊息所暗示的那樣,這是為了確保中間件管道的每個分支都有一對匹配的UseRouting和UseEndpoints。在我展示的示例中,缺少對 的呼叫branchApp.UseRouting(),因此會觸發錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/414076.html
標籤:
