我在网站上有多个控制器和区域。我想使用url没有控制器默认控制器名。因此,使用以下代码为route:
routes.MapRoute(
name: "WithOutController",
url: "{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
这工作。但适用于所有控制器,而不仅仅是默认控制器。我还尝试了以下代码:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "WithOutController",
url: "{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
但是这个代码只工作url与控制器。我想让它这样工作:
- 默认/指数:url (http://localhost: 2470/索引)
- 默认/登录:url (http://localhost: 2470/登录)
- 面板/指数:url (http://localhost: 2470/小组/索引)
没有default,不知道需要将多少操作映射到URL名字在上面。但如果只有两个,你可以试试这个:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultIndex",
url: "Index/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "DefaultLogin",
url: "Login/{id}",
defaults: new { controller = "Default", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
另一个选项是启用MapMvcAttributeRoutes用你想要的路线来装饰你的动作。
启用MapMvcAttributeRoutes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "About", id = UrlParameter.Optional }
);
}
那么在你的默认控制器中,你需要:
[Route("Index")]
public ActionResult Index()
{
return View();
}
[Route("Login")]
public ActionResult Login()
{
return View();
}
你的默认动作名必须和路由属性名不同。