c# - 如何将 RoutePattern 添加到 Endpoint 对象

标签 c# asp.net-core asp.net-mvc-routing

下面是一些简单的代码

public class Startup {
   public void ConfigureServices(IServiceCollection services) {
   }

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

      app.UseRouting();

      app.Use(async (context, next) => {
         var endpoint = context.GetEndpoint();  // <--------I put a debugger here
         await next();
      });

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

当断点被击中时,我可以看到一些属性已添加到 Endpoint 实例中,例如 RoutePattern 属性 enter image description here

但是 Endpoint 没有 RoutePattern 属性:

public class Endpoint {
   public Endpoint(RequestDelegate requestDelegate, EndpointMetadataCollection metadata, string displayName);
   public string DisplayName { get; }
   public EndpointMetadataCollection Metadata { get; }
   public RequestDelegate RequestDelegate { get; }

   public override string ToString();

那么RoutePattern属性是如何添加到Endpoint实例中的呢?

另一个问题是,当我运行应用程序时,断点总是被击中两次,而不是一次,为什么,因为只有一个请求,断点应该只击中一次?

最佳答案

Endpoint 类确实没有 RoutePattern 属性,但它的子类 RouteEndpoint 有此属性(Microsoft.AspNetCore.Routing.RouteEndpoint ),当你在调试器中观看时,你可以看到它。

enter image description here

为什么要点击两次,恐怕你的应用程序中有其他代码引导它,在我新创建的asp.net core MVC应用程序中,当应用程序启动时,它只点击一次,但在我的signalr mvc中项目中,由于signalr的连接,命中了两次。所以我认为你需要检查你的代码。

顺便说一下,这个文档是关于middleware execution order的可能有帮助。

关于c# - 如何将 RoutePattern 添加到 Endpoint 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70652475/

相关文章:

asp.net-mvc-4 - 重写或更改 asp.net MVC URL 中的路由?

c# - 将参数传递给 Controller ​​ ..但不在 URL 上

c# - 来自 Active Directory 的间歇性未知错误

c# - 使用 Nancy 返回包含有效 Json 的字符串

c# - 如何在 Visual Studio 2017 项目(新的 .csproj 文件格式)中设置 `OutputPath` 而目标框架不会混淆已解析的路径?

ASP.NET Core 通配符路由除外

asp.net-core - ASP.NET Core- 有没有办法使用自定义标签助手呈现一组元素?

asp.net-mvc-3 - 相对于 Asp.Net MVC 中的 View 路由图像?

c# - Linq 查询以获取子列表中的共享项

ASP.NET Core 3.1 项目在同一解决方案中引用了 .NET 4.7.2 项目错误 'System.Web.Configuration.WebConfigurationManager'