Asp.Net Core中RouteValueDictionary的路径

时间:2016-10-19 08:26:57

标签: c# asp.net-core asp.net-core-1.0

我需要从任意请求路径(与当前请求相关的)中提取路径数据(Controller,Action等),例如 / < / em>或 / account / manage 。在以前版本的Asp.Net Mvc中,可以这样完成:

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

此解决方案不是最佳解决方案,因为它需要完全合格的Url而不仅仅是请求路径。

1 个答案:

答案 0 :(得分:2)

您可以使用TemplateMatcher提取路线值:

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

示例用法:

var template = "{controller=Home}/{action=Index}/{id?}";
var routeValues = RouteMatcher.Match(template, "<your path>");

请参阅此文章:https://blog.markvincze.com/matching-route-templates-manually-in-asp-net-core/