【问题标题】:How can I find an endpoint from a url?如何从 url 中找到端点?
【发布时间】:2020-01-25 21:23:09
【问题描述】:

我正在使用端点路由,我想为给定的 url 和可能的请求方法找到正确的端点对象。如果我至少可以根据 url 找到 Endpoint,那会很有帮助。本质上,我希望实现以下方法。

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,但到目前为止我还没有想通。

【问题讨论】:

    标签: asp.net-core-3.1


    【解决方案1】:

    我不确定是否有更好的方法,但这似乎可行

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

    我从这个https://stackoverflow.com/a/59550580/384853得到了一些想法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 2020-07-04
      • 2021-04-01
      • 2011-06-20
      • 2021-11-10
      相关资源
      最近更新 更多