Manually match an url against the registered endpoints in .NET Core 3.0

前端 未结 1 540
逝去的感伤
逝去的感伤 2021-01-14 05:38

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 routeva

相关标签:
1条回答
  • 2021-01-14 06:07

    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.

    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 that does the actual routing i.e. calculating which endpoint will be invoked for a given request URL path.

    • EndpointMiddleware that invokes the endpoint.

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

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

    0 讨论(0)
提交回复
热议问题