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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With