如何在FastEndpoints运行时获取所有端点的列表?
运行时获取FastEndpoints端点列表的可行方案
因为FastEndpoints的EndPointData是内部类无法直接访问,我们可以利用其公开的元数据类型结合ASP.NET Core原生端点系统来提取所需的端点信息,具体实现如下:
核心实现代码
首先定义一个用于存储端点信息的DTO:
public class FastEndpointInfo { public string? GroupName { get; set; } public string EndpointName { get; set; } = string.Empty; public string Route { get; set; } = string.Empty; public string? HttpMethod { get; set; } }
接着创建服务类来筛选并提取FastEndpoints的端点信息:
using FastEndpoints; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; public class FastEndpointDiscoveryService { private readonly IEnumerable<Endpoint> _allEndpoints; public FastEndpointDiscoveryService(IEnumerable<Endpoint> endpoints) { _allEndpoints = endpoints; } public List<FastEndpointInfo> GetAllFastEndpoints() { var result = new List<FastEndpointInfo>(); foreach (var endpoint in _allEndpoints) { // 筛选出FastEndpoints定义的端点:检查元数据中是否包含EndpointDefinition var endpointDef = endpoint.Metadata.GetMetadata<EndpointDefinition>(); if (endpointDef is null) continue; // 提取HTTP方法 var httpMethodMeta = endpoint.Metadata.GetMetadata<HttpMethodMetadata>(); var httpMethod = httpMethodMeta?.HttpMethods.FirstOrDefault(); // 提取完整路由(包含所有前缀) var fullRoute = endpoint.RoutePattern?.RawText ?? string.Empty; result.Add(new FastEndpointInfo { GroupName = endpointDef.Group?.Name, EndpointName = endpointDef.EndpointType.Name, Route = fullRoute, HttpMethod = httpMethod }); } return result; } }
关键信息提取说明
- GroupName:从
EndpointDefinition.Group?.Name获取,未分组的端点此值为null - EndpointName:直接获取端点类的名称
endpointDef.EndpointType.Name - Route:通过
endpoint.RoutePattern.RawText拿到包含所有路由前缀的完整路径 - HttpMethod:从
HttpMethodMetadata中提取对应的HTTP请求方法
兼容原有ApiControllers逻辑
如果需要同时获取ApiControllers的端点信息,可以在同一个服务中保留你之前基于IActionDescriptorCollectionProvider和ControllerActionDescriptor的枚举逻辑,将两种端点的结果合并返回即可。
内容的提问来源于stack exchange,提问作者Onur Buyukcaglar
相关产品推荐
相关产品推荐

