2011-09-22 93 views
35

我需要一个实现,我可以在我的ASP.NET控制器上获得无限参数。这将是更好,如果我给你举个例子:ASP.NET MVC无限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>

注:

的问题没有得到很好的解释IMO,但我尽我所能,以适应它。 。 在随意调整它

回答

54

像这样:

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

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

嗯,看起来很整洁。要试一试。 – tugberk

+0

{* tags}在那里有什么作用?特别是,*。 – tugberk

+7

这是一个全面的参数。 http://msdn.microsoft.com/en-us/library/cc668201.aspx#handling_a_variable_number_of_segments_in_a_url_pattern – SLaks

25

渔获都将给你的原始字符串。如果你想要一个更优雅的方式来处理数据,你总是可以使用自定义路由处理程序。

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(); 
} 
5

万一有人要来此与MVC在.NET 4.0中,你必须要小心其中定义您的路线。我很高兴地去global.asax并添加这些答案(和其他教程)中建议的路线,并且无处可去。我的路线全部默认为{controller}/{action}/{id}。向URL添加更多的段给了我一个404错误。然后我发现了App_Start文件夹中的RouteConfig.cs文件。原来这个文件在Application_Start()方法中被global.asax调用。因此,在.NET 4.0中,确保您在那里添加自定义路由。 This article精美地覆盖它。