【问题标题】:Asp.net MVC 5 MapRoute for multiple routes用于多条路线的 Asp.net MVC 5 MapRoute
【发布时间】:2016-10-24 11:59:33
【问题描述】:

我在 RouteConfig 中有 3 条路线:

routes.MapRoute(
    name: "ByGroupName",
    url: "catalog/{categoryname}/{groupname}",
    defaults: new { controller = "Catalog", action = "Catalog" }
);
routes.MapRoute(
    name: "ByCatName",
    url: "catalog/{categoryname}",
    defaults: new { controller = "Catalog", action = "Catalog" }
);
routes.MapRoute(
    name: "ByBrandId",
    url: "catalog/brand/{brandId}",
    defaults: new { controller = "Catalog", action = "Catalog" }
);

这是我的动作控制器接收参数:

public ActionResult Catalog(
    string categoryName = null,
    string groupName = null,
    int pageNumber = 1,
    int orderBy = 5,
    int pageSize = 20,
    int brandId = 0,
    bool bundle = false,
    bool outlet = false,
    string query_r = null)
{
// ...
}

当我在视图中使用@Url.RouteUrl("ByBrandId", new {brandId = 5}) 的链接时,我在操作中得到一个参数“categoryname”="brand" 和brandId=0 而不是只有brandId=5...

当我使用“ByBrandId”routeurl 调用 "http://localhost:3453/catalog/brand/5" 时,我想在 actioncontroller 中获取 brandId=5...,相当于 "http://localhost:3453/catalog/Catalog?brandId=1"

谢谢

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing maproute


    【解决方案1】:

    您的路由配置错误。如果您传递 URL /Catalog/brand/something,它将始终匹配 ByGroupName 路由,而不是预期的 ByBrandId 路由。

    首先,您应该更正顺序。而且,除了可选的组名之外,前 2 条路线完全相同,因此您可以简化为:

    routes.MapRoute(
        name: "ByBrandId",
        url: "catalog/brand/{brandId}",
        defaults: new { controller = "Catalog", action = "Catalog" }
    );
    routes.MapRoute(
        name: "ByGroupName",
        url: "catalog/{categoryname}/{groupname}",
        defaults: new { controller = "Catalog", action = "Catalog", groupname = UrlParameter.Optional }
    );
    

    现在,当您使用 @Url.RouteUrl("ByBrandId", new {brandId = 5}) 时,它应该会为您提供预期的输出 /catalog/brand/5

    完整说明请参见Why map special routes first before common routes in asp.net mvc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-30
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多