【问题标题】:Custom MVC Routes自定义 MVC 路由
【发布时间】:2015-02-27 13:07:51
【问题描述】:

所以我刚刚在我的第一个大型 MVC 应用程序上进行路由,这让我很头疼。

所有/Category/Subcategory 都转到ProductController.Index(string category, string subcategory)。如果我没有指定子类别,它将显示该类别中的所有项目(福特、奥迪等)

如果我有这样的路线,则 url /Home/About 会转到 Product/Index,参数为:Category=Home, Subcategory=About

如果我将默认设置移到顶部,则 url /Car/Ford 不会去任何地方,因为我没有 CarController(我不希望每个类别都有一个控制器。)

我真的很想没有像 /store/Car/Ford 这样的其他细分市场..

我是否需要为每个“主要”类别创建一个路由并对名称进行硬编码? 帮我解决这个问题!

// http://localhost/Car/Ford (note: Car can be replaced by bike, plan, boat etc.)
routes.MapRoute(
    name: "AllProductsInCategoryOrSubcategory",
    url: "{category}/{subcategory}",
    defaults: new { controller = "Products", action = "Index", subcategory = UrlParameter.Optional }
);

// http://localhost/Car/Ford/ABC123/Explorer
// http://localhost/Car/Ford/ABC123
routes.MapRoute(
    name: "Kakel",
    url: "{category}/{subcategory}/{id}/{productName}",
    defaults: new { controller = "Products", action = "Details", productName = UrlParameter.Optional }
);

// http://localhost/Home/About
// http://localhost/Products/RenderImage/ABC123 (used to render image in details view)
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

【问题讨论】:

  • 如果没有你明确告诉它Car 实际上不是控制器,MVC 怎么知道/Products/RenderImage/ABC123/Car/Ford/ABC123 之间的区别?为什么路由不是/Products/Car/Ford/ABC123
  • 我想我可以为RenderImage 定制一个,但这并不能解决/Home/About 的问题。也许我想做的事情是不可能的?我猜像你说的另一个片段不是那个不好..

标签: c# asp.net-mvc routes


【解决方案1】:

你可以使用路由约束来解决这个问题。假设您的第一条路线 AllProductsInCategoryOrSubcategory 您可以像这样添加约束。这里我使用的是你目前只有一个类别,那就是汽车。

routes.MapRoute(
    name: "AllProductsInCategoryOrSubcategory",
    url: "{category}/{subcategory}",
    defaults: new { controller = "Products", action = "Index", 
                     subcategory = UrlParameter.Optional },
    new {category = "^car$"}
);

由于此路线限制,当类别名称为 car 时,MVC 将选择此路线。 重要的一点是您需要在路由约束之前添加默认值。因为在选择路由时,MVC 会先选择默认值,然后再应用约束。

【讨论】:

  • 这意味着我必须在每个类别的约束中添加一个词..?
  • 这只是一个例子。您可以根据需要准备更好的正则表达式,然后您可以在约束中使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多