ASP.NET MVC路由的无限URL参数

42
我需要一个能够在ASP.NET控制器上获取无限参数的实现。最好给你一个例子:

假设我有以下URL:

example.com/tag/poo/bar/poobar
example.com/tag/poo/bar/poobar/poo2/poo4
example.com/tag/poo/bar/poobar/poo89

如您所见,在example.com/tag/之后,将获得无限数量的标记,并且斜杠在此处将作为分隔符。

在控制器上,我想这样做:

foreach(string item in paramaters) { 

    //this is one of the url paramaters
    string poo = item;

}

有没有已知的方法来实现这个?我该如何从控制器中获取值?使用 Dictionary<string, string> 还是 List<string>

5个回答

61

就像这样:

routes.MapRoute("Name", "tag/{*tags}", new { controller = ..., action = ... });

ActionResult MyAction(string tags) {
    foreach(string tag in tags.Split("/")) {
        ...
    }
}

1
嗯,看起来非常整洁。我要试一试。 - tugberk
10
那是一个全能参数。http://msdn.microsoft.com/en-us/library/cc668201.aspx#handling_a_variable_number_of_segments_in_a_url_pattern - SLaks
什么?*代表通配符。我不知道你在问什么。 - SLaks
3
您只能使用 * 并且它必须始终是 catch-all 参数的第一个字符。它不是通配符,也不以任何形式作为通配符字符。这只是表示该路由参数将捕获从该点开始在您的 URL 中的所有内容。 - Robert Koritnik
“处理可变数量的片段”部分的直接链接为https://learn.microsoft.com/en-us/previous-versions/cc668201(v=vs.140)#handling-a-variable-number-of-segments-in-a-url-pattern。 - Eric Mutta
显示剩余2条评论

26

使用catch all会给你原始字符串。如果你想用更优雅的方式处理数据,可以使用自定义路由处理程序。

public class AllPathRouteHandler : MvcRouteHandler
{
    private readonly string key;

    public AllPathRouteHandler(string key)
    {
        this.key = key;
    }

    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var allPaths = requestContext.RouteData.Values[key] as string;
        if (!string.IsNullOrEmpty(allPaths))
        {
            requestContext.RouteData.Values[key] = allPaths.Split('/');
        }
        return base.GetHttpHandler(requestContext);
    }
} 

注册路由处理程序。

routes.Add(new Route("tag/{*tags}",
        new RouteValueDictionary(
                new
                {
                    controller = "Tag",
                    action = "Index",
                }),
        new AllPathRouteHandler("tags")));

在控制器中将标签作为数组获取。

public ActionResult Index(string[] tags)
{
    // do something with tags
    return View();
}

12

5

如果有人使用.NET 4.0中的MVC,请注意在哪里定义您的路由。我一直在按照这些答案(以及其他教程)的建议,去到global.asax添加路由,却得不到任何结果。我的路由全部默认为{controller}/{action}/{id}。在URL中添加更多片段会导致404错误。后来我发现了App_Start文件夹中的RouteConfig.cs文件。原来这个文件是在Application_Start()方法中被global.asax调用的。因此,在.NET 4.0中,请确保在那里添加您的自定义路由。这篇文章阐述得非常好。


1
在ASP.NET Core中,您可以在路由中使用*。例如:[HTTPGet({*id})]。这段代码可以用于多个参数或者当使用带有斜杠的字符串时,使用它们来获取所有参数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接