Just wanted to share a code about endpoint routing that I was able to write after time of research.
Problem Statement:
Given a URL path of an MVC application, retrieve the route values such as area, controller, and action name.
e.g.:
path=”/Home/Contact?id=123″
returns {“controller”: “Home”, “action”: “Contact”, “id”:123}
Solution:
public class MyRouteEndpointService
{
private EndpointDataSource _endpointDataSource;
public MyRouteEndpointService(EndpointDataSource endpointDataSource)
{
_endpointDataSource = endpointDataSource;
}
public (RouteValueDictionary, RouteEndpoint) GetRouteInfo(string path)
{
var endpoints = _endpointDataSource.Endpoints.Cast().OrderBy(c => c.Order).ToList();
RouteValueDictionary matchedRouteData = null;
RouteEndpoint matchedEndpoint = null;
foreach (var endpoint in endpoints)
{
var matcher = new TemplateMatcher(TemplateParser.Parse(endpoint.RoutePattern.RawText),
new RouteValueDictionary(endpoint.RoutePattern.Defaults));
var routeData = new RouteValueDictionary();
if (matcher.TryMatch(path, routeData))
{
matchedEndpoint = endpoint;
matchedRouteData = routeData;
break;
}
}
return (matchedRouteData, matchedEndpoint);
}
}