你可以这样做:
routes.MapRoute("Default", "{category}/{subcategory}",
new { controller = "CategoryController", action = "Display", id = "" }
);
然后在你的控制器中:
public class CategoryController : Controller
{
public ActionResult Display(string category, string subcategory)
{
// do something here.
}
}
不要将上述任何路线用于所有路线(除非您在上述路线之前指定明确的路线,否则您不能有关于页面等)。
但是,您可以包含自定义约束以将路由限制为仅现有类别。就像是:
public class OnlyExistingCategoriesConstraint : IRouteConstraint
{
public bool Match
(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
var category = route.DataTokens["category"];
//TODO: Look it up in your database etc
// fake that the category exists
return true;
}
}
您在路线中使用的是这样的:
routes.MapRoute("Default",
"{category}/{subcategory}",
new { controller = "CategoryController", action = "Display", id = "" },
new { categoryExists = new OnlyExistingCategoriesConstraint() }
);
这样它就不会干扰您定义的其他路线。