我无法捕获所有在MVC中工作的路径。我试图实现此question中显示的内容,但它不起作用。我有一个名为OnlineController的控制器,带有一个Index动作。我的RouteConfig.cs设置如下:
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 }
);
routes.MapRoute("RouteName", "{*url}", new { controller =
"Online", action = "Index" });
}
浏览以下网址
Blockquote http://mysite/online/something
给出404.为什么它没有被捕获并重定向到Online控制器上的索引操作?
答案 0 :(得分:2)
如果要捕获所有路线,则应删除"Default"
路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
routes.MapRoute("RouteName", "{*url}", new { controller = "Online", action = "Index" });
}
路线按照映射顺序选择,您的网址与"Default"
路线匹配。
如果您想捕获现有控制器和操作的一些路线,您可以使用"Default"
路线,但有约束条件:
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 },
constraints: new { controller = "Home|Home2", action = "Index|Index2"}
);
routes.MapRoute("RouteName", "{*url}", new { controller =
"Online", action = "Index" });
}
现在,如果控制器名称为"Home"
或"Home2"
且操作名称为"Index"
或"Index2"
,则这些路由将由现有控制器和操作处理,如果其他名称 - 由"Online"
控制器