我知道它的情况更相似(因此对此有超过5,600 questions),但我现在已经坐了几天了所以我想现在是时候问这个问题了。问题
我想在我的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的routing debugger调试我的代码,但没有运气。我有什么想法吗?
答案 0 :(得分:2)
问题在于您的最后两个自定义路线。所有路由框架必须使用的只是URL中的一个令牌,以及两个可能匹配的路由。例如,如果您尝试转到网址/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 = "" }
);
这样,任何实际的动作名称都将首先匹配。