创建带有正斜杠的ASP.Net MVC路由

时间:2018-07-05 00:27:12

标签: c# asp.net-mvc asp.net-mvc-routing

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

public ActionResult Transactions(string type) {}

要访问此控制器并传递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]+$" }
);

但是现在如果我传递这样的网址

  

www.mysite.com/controller/transactions/made

操作中字符串类型的值为空

我允许这样做还是做错了什么?

这是我的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
    }
  );


}

1 个答案:

答案 0 :(得分:4)

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" }   
);