创建仅包含正斜杠的 ASP.Net MVC 路由

Creating a ASP.Net MVC route with just forward slashes

我在控制器中有一个看起来像这样的动作

public ActionResult Transactions(string type) {}

要访问此控制器并传入类型 属性 值,我必须输入

www.mysite/controller/transactions?type=sometype

但是我想要传递这样的东西

www.mysite.com/controller/transactions/sometype

所以我在 RouteConfig.cs 文件中创建了一个路由配置参数,像这样

routes.MapRoute(
   name: "TransactionRoute",
   url: "user/transactions/{type}",
   defaults: new { controller = "user", action = "transactions", type = "made" },
   constraints: new { title = @"^[A-Za-z]+$" }
);

但现在如果我像这样传递 url

www.mysite.com/controller/transactions/made

action中字符串类型的值为null

我可以这样做还是我做错了什么?

这是我的 routeconfig.cs 文件

public static void RegisterRoutes(RouteCollection routes) {
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
    name: "TransactionRoute",
    url: "user/transactions/{type}",
    defaults: new {
      controller = "user", action = "transactions", type = "made"
    },
    constraints: new {
      title = @ "^[A-Za-z]+$"
    }
  );

  routes.MapRoute(
    name: "RateRoute",
    url: "rate/event/{id}",
    defaults: new {
      controller = "rate", action = "event"
    },
    constraints: new {
      id = @ "\d+"
    }
  );

  routes.MapRoute(
    name: "ReviewRoute",
    url: "rate/review/{id}",
    defaults: new {
      controller = "rate", action = "review"
    },
    constraints: new {
      id = @ "\d+"
    }
  );

  routes.MapRoute(
    name: "SpaceCleanRoute",
    url: "space/{id}",
    defaults: new {
      controller = "space", action = "index", id = UrlParameter.Optional
    },
    constraints: new {
      id = @ "\d+"
    }
  );

  routes.MapRoute(
    name: "SpacePendingRoute",
    url: "space/{id}/{pending}",
    defaults: new {
      controller = "space", action = "index", pending = UrlParameter.Optional
    },
    constraints: new {
      id = @ "\d+"
    }
  );


  routes.MapRoute(
    name: "PublicSpaceRoute",
    url: "space/public/{title}",
    defaults: new {
      controller = "space", action = "public"
    },
    constraints: new {
      title = @ "^[A-Za-z0-9-]+$"
    }
  );

  routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new {
      controller = "Home", action = "Index", id = UrlParameter.Optional
    }
  );


}

www.mysite.com/user/transactions/sometype 应该匹配 TransactionRoute

此外,我认为不需要基于路由模板的 title 约束。

删除 title 约束

routes.MapRoute(
   name: "TransactionRoute",
   url: "user/transactions/{type}",
   defaults: new { controller = "user", action = "transactions", type = "made" }   
);