gpt4 book ai didi

Asp.net MVC 5 MapRoute 用于多个路由

转载 作者:行者123 更新时间:2023-12-02 15:35:55 30 4
gpt4 key购买 nike

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

这是我接收参数的 Action Controller :

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)
{
// ...
}

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

当我使用“ByBrandId”routeurl调用“http://localhost:3453/catalog/brand/5”时,我想在actioncontroller中获取brandId=5...,相当于“http://localhost:3453/catalog/Catalog?brandId=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以获得完整的解释。

关于Asp.net MVC 5 MapRoute 用于多个路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37969797/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com