ASP.NET MVC Hierarchy Url Routing

2019-07-19 08:34发布

I have a problem

My route have an extra paramater after hierarchical category.

/2009/World/Asia/08/12/bla-bla-bla

asp.net mvc does not support this because my routing should be

{year}/{*category}/{month}/{day}/{name}

i tried use constraint like

year = @"(\d{4})",category = @"((.+)/)+", month = @"(\d{2})", day = @"(\d{2})"

but i cannot find any solution.

Is there any comment?

Thank you

3条回答
做自己的国王
2楼-- · 2019-07-19 09:12

If I understood well, you want to limit and put some constraints on values can pass as routing sections, You can do it with Route Constraint. Plaese read Creating a Route Constraint (C#) and you will find how that is possible. You can do it same as below:

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"\d+" }
 );

The regular expression \d+ matches one or more integers. This constraint causes the Product route to match the following URLs:

/Product/3

/Product/8999

But not the following URLs:

/Product/apple

/Product

Additionally you could write your custom route constraint, Please read Creating a Custom Route Constraint (C#) and see below sample I just copied from This post by Guy Burstein that I think you find it useful:

public class FromValuesListConstraint : IRouteConstraint
    {
      public FromValuesListConstraint(params string[] values)
      {
        this._values = values;
      }

      private string[] _values;

      public bool Match(HttpContextBase httpContext, 
        Route route, 
        string parameterName, 
        RouteValueDictionary values, 
        RouteDirection routeDirection)
      {
        // Get the value called "parameterName" from the 
        // RouteValueDictionary called "value"
        string value = values[parameterName].ToString();

        // Return true is the list of allowed values contains 
        // this value.
        return _values.Contains(value);
      }
    }

As Guy said: In order to implement a Custom Route Constraint, you should create a class that inherits from IRouteConstraint, and implement the Match method.

Hope this help.

查看更多
叛逆
3楼-- · 2019-07-19 09:24

I'm pretty sure that the route handler tokenizes on the slash character so you won't be able to have a category that includes a slash -- though escaping it might work, not sure about that. You might want to format your URL as:

/2009/World+Asia/08/12/bla-bla-bla

This should translate the category as "World Asia".

If that doesn't work then perhaps you need another route that matches on subcategory as well.

{year}/{category}/{subcategory}/{month}/{day}/{name}
查看更多
老娘就宠你
4楼-- · 2019-07-19 09:31

Add another rule to your routing with the name parameter.

查看更多
登录 后发表回答