我正在开发一个 Web ASP.NET MVC,我希望我的 Web 上的所有页面都有一个独特的 URL 表单,如下所示:WebName /{ Title }。这是我的客户的要求。
例如:store.com/chicken-pizza和store.com/how-to-cook-beefsteak,但不是:store.com/foods/chicken-pizza和store.com/recipe/how-to-cook-beefsteak
我尝试使用 RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
/* store.com/foods => This works well */
routes.MapRoute(
name: "List-Foods",
url: "foods",
defaults: new { controller = "Food", action = "ListFoods", id = UrlParameter.Optional }
);
/* store.com/chicken-pizza, store.com/cheese-sandwich,... => This works well */
routes.MapRoute(
name: "Detail-Food",
url: "{title}",
defaults: new { controller = "Food", action = "FoodDetail", id = UrlParameter.Optional }
);
/* store.com/recipes => This works well */
routes.MapRoute(
name: "List-Recipes",
url: "recipes",
defaults: new { controller = "Recipe", action = "ListRecipes", id = UrlParameter.Optional }
);
/* store.com/how-to-make-beefsteak,
store.com/instructions-for-making-cookies,..
=> Conflict occurred... this route can't be touch because it
has the same url form as Details-Food (url:{title}) */
routes.MapRoute(
name: "Detail-Recipe",
url: "{title}",
defaults: new { controller = "Recipe", action = "RecipeDetail", id = UrlParameter.Optional }
);
...............
}
我意识到 routes.MapRoute(s) 不能具有相同的 URL 形式(url:"{title}")。这对于url:"foods"(获取食物列表)和url:"recipes"(获取食谱列表)不是问题,因为我在 routes.Maproute 中指定了单词(foods and recipes)。此外,我可以通过 Detail-Food 路线轻松获取 {title} 的任何提要的详细信息。但是,问题出现在 Detail-Recipe 路由中,因为它与 Detail-Food 路由具有相同的 url 形式(url:{title}),我无法触摸 Recipe/RecipeDetail 来获取数据。