asp.net mvc 路由 - 映射操作而不是控制器

asp.net mvc routing - map actions not controllers

我知道它更像是相同的(所以在这方面有超过 5,600 questions),但我已经坐了几天了,所以我想现在是时候了问一个问题。

我的要求

我想在我的 asp.net mvc 应用程序中使用以下路由:

  1. myapp.com/sigin -> Controller = Account,Action = SignIn
  2. myapp.com/signout -> Controller = Account,Action = SignOut
  3. myapp.com/joe.smith -> Controller = User, Action = Index
  4. myapp.com/joe.smith/following -> Controller = User, Action = Following
  5. myapp.com/joe.smith/tracks -> Controller = Tracks, Action = Index
  6. myapp.com/about -> Controller = About, Action = Index
  7. 任何其他默认路由,这就是我将标准路由留在那里的原因。

我的代码

 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 调试我的代码,但没有成功。知道我做错了什么吗?

问题出在您最后两条自定义路由中。所有路由框架必须处理的只是 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 = "" }
 );

这样,任何实际的操作名称都会首先匹配。