[英]asp.net mvc routing - map actions not controllers
我知道这差不多 (SO对此有5600多个问题 ),但是我已经坐在这个问题上几天了,所以我想是时候提出问题了。
我想在asp.net mvc应用程序中使用以下路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "About",
url: "about",
defaults: new { controller = "About", action = "Index" }
);
routes.MapRoute(
name: "MyTracks",
url: "{username}/tracks",
defaults: new { controller = "MyTracks", action = "Index" }
);
routes.MapRoute(
name: "MyTunes",
url: "{username}/tunes",
defaults: new { controller = "MyTunes", action = "Index" }
);
routes.MapRoute(
name: "MyProfile",
url: "{username}",
defaults: new { controller = "User", action = "Index"},
constraints: new { username = "" }
);
routes.MapRoute(
name: "Account",
url: "{action}",
defaults: new { controller = "Account" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
路由3和4根本不起作用,因为它们与路由1和2混淆了。我曾尝试使用Phil Haack的路由调试器调试代码 ,但是没有运气。 有什么想法我做错了吗?
问题出在您的最后两个自定义路线中。 所有路由框架必须使用的只是URL中的单个令牌,以及两个与其匹配的可能路由。 例如,如果您尝试访问URL /signin
,那么路由框架应该如何知道没有用户名为“ signin”的用户。 对于人类来说,这很明显,应该发生什么,但是机器只能做很多事情。
您需要以某种方式区分路线。 例如,您可以执行u/{username}
。 这足以帮助路由框架。 简而言之,您需要在用户路由之前为每个帐户操作定义自定义路由。 例如:
routes.MapRoute(
name: "AccountSignin",
url: "signin",
defaults: new { controller = "Account", action = "Signin" }
);
// etc.
routes.MapRoute(
name: "MyProfile",
url: "{username}",
defaults: new { controller = "User", action = "Index"},
constraints: new { username = "" }
);
这样,任何实际的动作名称都将首先匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.