ASP.NET MVC Route的无限URL参数

tug*_*erk 38 asp.net asp.net-mvc asp.net-mvc-routing asp.net-mvc-3

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

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

example.com/tag/poo/bar/poobar
example.com/tag/poo/bar/poobar/poo2/poo4
example.com/tag/poo/bar/poobar/poo89
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它将获得无限数量的标记,example.com/tag/并且斜杠将成为此处的分隔符.

在控制器上我想这样做:

foreach(string item in paramaters) { 

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

}
Run Code Online (Sandbox Code Playgroud)

有没有任何已知的方法来实现这一目标?如何从控制器获取值?用Dictionary<string, string>List<string>

注意 :

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

SLa*_*aks 58

像这样:

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

ActionResult MyAction(string tags) {
    foreach(string tag in tags.Split("/")) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个包罗万象的参数.http://msdn.microsoft.com/en-us/library/cc668201.aspx#handling_a_variable_number_of_segments_in_a_url_pattern (8认同)
  • @tugberk:你只能使用*,它总是必须是一个catch-all参数的第一个字符.它不是任何形状或形式的通配符.它只是意味着此路由参数将从您的URL中的该点开始捕获所有内容. (3认同)

The*_*ing 26

所有捕获都将为您提供原始字符串.如果您想要一种更优雅的方式来处理数据,您可以始终使用自定义路由处理程序.

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);
    }
} 
Run Code Online (Sandbox Code Playgroud)

注册路由处理程序.

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

将标记作为控件中的数组获取.

public ActionResult Index(string[] tags)
{
    // do something with tags
    return View();
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ogo 5

为了防止有人在.NET 4.0中使用MVC,你需要定义路由时要小心.我很高兴地global.asax按照这些答案(以及其他教程)中的建议添加路线并且无处可去.我的路线都是违约的{controller}/{action}/{id}.将更多段添加到URL会给我404错误.然后我在App_Start文件夹中发现了RouteConfig.cs文件.事实证明,该文件global.asaxApplication_Start()方法中被调用.因此,在.NET 4.0中,请确保在那里添加自定义路由.这篇文章很精美.