我有一个HomeController
我有2 ActionResults
说Index
和Projects
。现在我的RouteConfig.cs
添加了以下路线:
routes.MapRoute(
name: "Default_1",//Changed this to some other name
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",//Made this name as Default
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Projects", id = UrlParameter.Optional }
);
因此,根据上述配置,我希望默认情况下用户将重定向到/Home/Projects
。但它又重定向到Index
行动。 为什么不重定向到Projects
行动?我们这里有多条路线吗?Default
名称不会被视为默认网址?
答案 0 :(得分:2)
注册路线时,请将您的特定路线定义放在默认路线定义之前。 路线注册的顺序很重要。
routes.MapRoute(
name: "Project",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Projects", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
使用此配置,任何来的请求都将重定向到您的Home/Projects
,因为网址格式仍然是通用格式({controller}/{action}/{id}
)。所以我猜你真的是这样的。
routes.MapRoute(
name: "Project",
url: "projects/{id}",
defaults: new { controller = "Home", action = "Projects", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
这会将请求http://yourSite.com/Projects
发送到Home/Projects
或者您可以使用属性路由在Projects控制器中定义此路由模式。要启用属性路由,您可以使用MapMvcAttributeRoutes
RegisterRoutes
方法调用RouteConfig.cs
方法。您仍将保留默认路由定义。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
在您的ProjectsController中
[Route("Projects/{id?}")]
public ActionResult Index(int? id)
{
//check id value and return something
}