Path to RouteValueDictionary in Asp.Net Core
asp.net-core, asp.net-core-1.0, c#
Solution
You can use `TemplateMatcher` to extract route values:
public class RouteMatcher
{
public static RouteValueDictionary Match(string routeTemplate, string requestPath)
{
var template = TemplateParser.Parse(routeTemplate);
var matcher = new TemplateMatcher(template, GetDefaults(template));
var values = new RouteValueDictionary();
var moduleMatch = matcher.TryMatch(requestPath, values);
return values;
}
// This method extracts the default argument values from the template.
private static RouteValueDictionary GetDefaults(RouteTemplate parsedTemplate)
{
var result = new RouteValueDictionary();
foreach (var parameter in parsedTemplate.Parameters)
{
if (parameter.DefaultValue != null)
{
result.Add(parameter.Name, parameter.DefaultValue);
}
}
return result;
}
}
And example usage:
var template = "{controller=Home}/{action=Index}/{id?}";
var routeValues = RouteMatcher.Match(template, "<your path>");
See this article: https://blog.markvincze.com/matching-route-templates-manually-in-asp-net-core/
Problem
I need to extract the route data (Controller, Action etc) from an arbitrary request path (not related to the current request) such as / or /account/manage. In previous versions of Asp.Net Mvc this could be accomplished like this: ``` var request = new HttpRequest(null, "http://localhost:3333/Home/About", "testvalue=1"); var response = new HttpResponse(new StringWriter()); var httpContext = new HttpContext(request, response); var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); var values = routeData.Values; // The following should be true for initial version of mvc app. values["controller"] == "Home" values["action"] == "Index" ``` Source This solution is not optimal since it requires a fully qualified Url instead of just a request path.