手动将URL与.NET Core 3.0中已注册的终结点匹配 [英] Manually match an url against the registered endpoints in .NET Core 3.0

查看:157
本文介绍了手动将URL与.NET Core 3.0中已注册的终结点匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,我想将url与所有已注册的路由进行匹配,以查看是否存在匹配项.

For my application I would like to match an url against all the registered routes to see there is a match.

当有匹配项时,我想从匹配项中提取路由值.

When there is a match, I would like to extract the routevalues from the match.

我在ASP.NET Core 2.1中可以使用此功能,但是我似乎无法像在.NET Core 3中那样检索路由.

I got this working in ASP.NET Core 2.1, but i do not seem to be able to retrieve the routes the way they are retrieved in .NET Core 3

有效的ASP.NET Core 2.1示例:

Working ASP.NET Core 2.1 sample:

string url = "https://localhost/Area/Controller/Action";

// Try to match against the default route (but can be any other route)
Route defaultRoute = this._httpContextAccessor.HttpContext.GetRouteData().Routers.OfType<Route>().FirstOrDefault(p => p.Name == "Default");

RouteTemplate defaultTemplate = defaultRoute.ParsedTemplate;
var defaultMatcher = new TemplateMatcher(defaultTemplate, defaultRoute.Defaults);
var defaultRouteValues = new RouteValueDictionary();
string defaultLocalPath = new Uri(url).LocalPath;

if (!defaultMatcher.TryMatch(defaultLocalPath, defaultRouteValues))
{
    return null;
}

string area = defaultRouteValues["area"]?.ToString();
string controller = defaultRouteValues["controller"]?.ToString(); 
string actiondefaultRouteValues["action"]?.ToString();

是否可以获取所有已注册的端点(模板)并与这些模板进行匹配?

Is there a way to obtain all registered endpoints (templates) and match against these templates?

推荐答案

在ASP.NET Core 2.1和更低版本中,路由是通过实现IRouter接口将传入的URL映射到处理程序来处理的.通常,您将不必依赖直接添加到中间件管道末端的MvcMiddleware实现.

In ASP.NET Core 2.1 and below, routing was handled by implementing the IRouter interface to map incoming URLs to handlers. Rather than implementing the interface directly, you would typically rely on the MvcMiddleware implementation added to the end of your middleware pipeline.

在ASP.NET Core 3.0中,我们使用端点路由,因此路由步骤与端点的调用是分开的.实际上,这意味着我们有两种中间件:

In ASP.NET Core 3.0, we use endpoint routing, so the routing step is separate from the invocation of the endpoint. In practical terms that means we have two pieces of middleware:

  • EndpointRoutingMiddleware执行实际路由,即 计算将为给定请求URL调用哪个端点 路径.

  • EndpointRoutingMiddleware that does the actual routing i.e. calculating which endpoint will be invoked for a given request URL path.

EndpointMiddleware调用端点.

因此,您可以尝试以下方法将url与所有已注册的路由进行匹配,以查看asp.net core 3.0中是否存在匹配项.

So you could try the following method to match an url against all the registered routes to see there is a match in asp.net core 3.0.

    public class TestController : Controller
  {
    private readonly EndpointDataSource _endpointDataSource;

    public TestController ( EndpointDataSource endpointDataSource)
    {
        _endpointDataSource = endpointDataSource;
    }

    public IActionResult Index()
    {
        string url = "https://localhost/User/Account/Logout";

        // Return a collection of Microsoft.AspNetCore.Http.Endpoint instances.
        var routeEndpoints = _endpointDataSource?.Endpoints.Cast<RouteEndpoint>();
        var routeValues = new RouteValueDictionary();
        string LocalPath = new Uri(url).LocalPath;

        //To get the matchedEndpoint of the provide url
        var matchedEndpoint = routeEndpoints.Where(e => new TemplateMatcher(
                                                                    TemplateParser.Parse(e.RoutePattern.RawText),
                                                                    new RouteValueDictionary())
                                                            .TryMatch(LocalPath, routeValues))
                                            .OrderBy(c => c.Order)
                                            .FirstOrDefault();
        if (matchedEndpoint != null)
        {
            string area = routeValues["area"]?.ToString();
            string controller = routeValues["controller"]?.ToString();
            string action = routeValues["action"]?.ToString();
        }
        return View();
    }
   }

您可以参考此博客有关ASP.NET Core 3.0中端点路由的更多详细信息.

You could refer to this blog for more details on the endpoint routing in ASP.NET Core 3.0.

这篇关于手动将URL与.NET Core 3.0中已注册的终结点匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆