我正在使用Endpoint Routing,我想为给定的URL和可能的请求方法找到正确的Endpoint对象。如果我至少可以根据URL找到端点,那将很有帮助。本质上,我正在寻求实现以下方法。
public Endpoint GetEndpoint(HttpContext httpContext, string url, string requestMethod)
{
// I can get all of the endpoints
var endpointDataSource = httpContext.RequestServices.GetService<EndpointDataSource>();
var endpoints = endpointDataSource.Endpoints;
// But I'm not sure what to do here
}
我认为也许可以使用DefaultLinkParser.cs,但到目前为止,我还没有弄清楚。
答案 0 :(得分:0)
我不确定是否有更好的方法,但这似乎可行
public Endpoint GetEndpoint(HttpContext httpContext, string url, string requestMethod)
{
var routeValues = new RouteValueDictionary();
var endpointDataSource = httpContext.RequestServices.GetService<EndpointDataSource>();
var endpoints = endpointDataSource.Endpoints.OfType<RouteEndpoint>();
foreach (var endpoint in endpoints)
{
var templateMatcher = new TemplateMatcher(TemplateParser.Parse(endpoint.RoutePattern.RawText), new RouteValueDictionary());
if (!templateMatcher.TryMatch(url, routeValues)) continue;
var httpMethodAttribute = endpoint.Metadata.GetMetadata<HttpMethodAttribute>();
if (httpMethodAttribute != null && !httpMethodAttribute.HttpMethods.Any(x => x.Equals(requestMethod, StringComparison.OrdinalIgnoreCase))) continue;
return endpoint;
}
return null;
}
中得到了一些想法