如何在ASP.NET MVC中实现“自然”url方案路由表

时间:2011-02-16 14:40:58

标签: c# asp.net-mvc asp.net-mvc-routing plural singular

我想指定我的路由表,以便他们感觉更“自然”

/Products
/Product/17
/Product/Edit/17
/Product/Create

接近默认配置,但“Index”操作将映射到控制器名称的倍数形式,“Details”操作将直接映射到直接跟在控制器名称后面的项目的ID。

我知道我可以通过明确定义这样的特殊路由映射来实现这一点:

routes.MapRoute(
    "ProductsList",
    "Products",
    new { controller = "Product", action = "Index" }
);
routes.MapRoute(
    "ProductDetails",
    "Product/{id}",
    new { controller = "Product", action = "Details" }
);

/*
 * Ditto for all other controllers
 */

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

上面的代码对我的口味来说过于冗长,并且有一个缺点,即每个控制器需要至少提及两次才能预先应用这个url模式。

是否有某种方法可以概括这一点,或者在这种情况下我是否需要手工劳动?

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

routes.MapRoute(
                "ProductsList",
                "{pluralizedControllerName}",
                new { controller = "Home", action = "Index" },
                new { pluralizedControllerName = new PluralConstraint() }
                );

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

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

注意第二条路线中的约束,它确保第二条路线不会挑选/Product/Create,以便将其映射为第三条路线。

对于路线测试,您可以使用routedebugger,并为路线编写单元测试,请尝试MvcContrib-TestHelper。您可以使用NuGet获得两者。

编辑:

您可以使用此simple pluralizer,然后实现以下内容:

public class PluralConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            List<string> names = GetControllerNames();//get all controller names from executing assembly
            names.ForEach(n => n.Pluralize(n));
            return names.Contains(values[parameterName]);
        }
    }