c# - Asp.Net Core 中 RouteValueDictionary 的路径

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

我需要从任意请求路径(与当前请求相关)提取路由数据(Controller、Action等),例如//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 而不仅仅是一个请求路径。

最佳答案

您可以使用 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/

关于c# - Asp.Net Core 中 RouteValueDictionary 的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40125980/

相关文章:

unit-testing - ExpectedException xunit .net core

C# : Blocking a function call until condition met

c# - 如何从 powerpoint 中读取数据

c# - 如何为类生成 JSON 示例值,就像 Swagger 所做的示例响应一样?

javascript - 如何存储 DIV 值? (鹅毛笔)

c# - 如何检测我的 Asp.Net Core 应用程序正在运行的操作系统?

c# - 现在,从 ASP .Net Core 1.0.0-rc2-final 交换到 1.0.0 时,JSON 属性变为小写

c# - 如何在 ASP.NET Core 1.0 RC2 中将实例注册到 ServiceCollection

c# - 更改静态无效C#中的标签文本

javascript - 在 MVC 4.0 中捆绑 javascript 文件