【问题标题】:Routes in ASP.NET MVC 5ASP.NET MVC 5 中的路由
【发布时间】:2017-02-03 07:38:02
【问题描述】:

我的要求是我需要为同一个控制器/动作方法设置多个路由。

如果用户输入 url http://localhost:xxxx/home/index ,它将针对“home”控制器的“index”操作方法。

我还希望 "http://localhost:xxxx/products" 和 "http://localhost:xxxx/categories" 指向 "home" 控制器的 "index" 操作方法。

我能够通过添加两条路线“类别”和“产品”来实现这一点,如下所述,它工作正常。

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

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


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

我的问题是,有什么办法可以将这两条路线“类别”和“产品”合二为一吗?

【问题讨论】:

  • 简短回答:否。(由于您在前 2 条路线中没有{id} 的段,您不妨删除id = UrlParameter.Optional)。话虽如此,您可以创建路线约束,但这可能不值得。
  • 路由属性的正则表达式过滤器可能是你的朋友,我可以用它做一些非常相似的事情。这里有一些信息:stackoverflow.com/questions/25077406/…
  • 如果您可以进行属性路由(但实际上不合并它),那将是干净的[Route("Home/Index")] [Route("Products")] [Route("Categories")] public ActionResult Index() { return View(); }
  • @开发者,MVC 5支持属性路由?
  • @CleanCrispCode - 确实如此 - blogs.msdn.microsoft.com/webdev/2013/10/17/…

标签: asp.net-mvc


【解决方案1】:

您可以通过向您的路线添加约束来实现此目的。

将整个路径作为一个参数,然后分配一个正则表达式规则来匹配这个参数。

routes.MapRoute(
    name: "IndexMapper",
    url: "{alternateIndexName}",
    defaults: new { controller="Home", action="Index" },
    constraints: new { alternateIndexName="(categories)|(products)"}
);

https://msdn.microsoft.com/en-us/library/cc668201.aspx#Anchor_6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2015-04-06
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2015-12-22
    相关资源
    最近更新 更多