【问题标题】:what does Map() fork the pipeline is called between the EndpointRoutingMiddleware and EndpointMiddleware mean?Map() fork 在 EndpointRoutingMiddleware 和 EndpointMiddleware 之间调用管道是什么意思?
【发布时间】:2022-01-17 10:55:54
【问题描述】:

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();
   });
}

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

【问题讨论】:

    标签: c# asp.net-core routes


    【解决方案1】:

    以下示例练习了您突出显示的代码:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2011-09-05
      • 2017-05-07
      • 1970-01-01
      • 2021-08-17
      相关资源
      最近更新 更多