Endpoint Routing – .Net Core

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

endpoint

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s