ASP.NET MVC Route的无限URL参数

时间:2011-09-22 13:36:54

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-routing

我需要一个实现,我可以在ASP.NET控制器上获得无限参数。如果我举个例子,那会更好:

我们假设我将有以下网址:

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>

  

注意:

     

IMO没有很好地解释这个问题,但我尽力适应它。   in。随意调整它

5 个答案:

答案 0 :(得分:57)

像这样:

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

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

答案 1 :(得分: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();
}

答案 2 :(得分:11)

这叫做catch-all

tag/{*tags}

答案 3 :(得分:5)

如果有人在.NET 4.0中使用MVC进行此操作,您需要小心 来定义路由。我很高兴地去global.asax并按照这些答案(以及其他教程)中的建议添加路线并且无处可去。我的路线都默认为{controller}/{action}/{id}。将更多段添加到URL会给我404错误。然后我在App_Start文件夹中发现了RouteConfig.cs文件。事实证明,此文件由global.asax方法中的Application_Start()调用。因此,在.NET 4.0中,请确保在那里添加自定义路由。 This article很好地涵盖了它。

答案 4 :(得分:0)

在asp .net core中你可以在路由中使用* 例如

[HTTPGet({*id})]

这段代码可以多参数或者当使用带斜杠的发送字符串时使用它们来获取所有参数