Asp.net-Mvc-5

MVC 5 AttributeRouting 包羅萬象

  • May 6, 2015

如何在 MVC 中使用新的屬性路由創建一條擷取所有路由

我試過這個: [Route("{pagenode}", Order = 999)]

但是當我有一個命名路線時 [Route("contact"]

我得到了"Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL."錯誤。

您不能使用 Attribute 路由來執行此操作,請使用 MVC4 方式執行此操作:

在你的路由映射器中映射一個路由,如下所示:

routes.MapRoute("RouteName","{*url}",new { controller = "YourFancyController", action = "YourAction" });

這將是您的包羅萬象的路線。

如果您想將所有路由映射到他們的控制器,您可以這樣做:

public static void RegisterRoutes(RouteCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

   routes.MapMvcAttributeRoutes();

   AreaRegistration.RegisterAllAreas();

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

如果路徑中的第一個“目錄”是固定的,這可以通過屬性路由來完成。

例如,要匹配任何命中or/questions然後你會使用./questions/4``/questions/answers/42``[Route("questions/{*catchall}"]

引用自:https://stackoverflow.com/questions/22538574