ASP.NET MVC Hierarchy Url Routing
Asked Answered
T

3

2

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

Tung answered 9/12, 2009 at 15:11 Comment(0)
G
1

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}
Genniegennifer answered 9/12, 2009 at 15:22 Comment(0)
K
0

Add another rule to your routing with the name parameter.

Kathykathye answered 9/12, 2009 at 15:21 Comment(0)
U
0

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.

Unorthodox answered 1/5, 2018 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.