gpt4 book ai didi

asp.net-mvc - MVC 路由可选字符串参数和难看的 url

转载 作者:行者123 更新时间:2023-12-04 02:46:01 25 4
gpt4 key购买 nike

我在 4.5.1 上使用 mvc 5.2.3 并想要这些 url

  • /耐克/鞋子
  • /耐克/鞋子/运行
  • /耐克/衬衫/2002342345
  • /耐克/鞋子/运行/98765432234

我的 Controller 有:

[HttpGet]
[Route("{brand}/{category}/{subcategory}/{page:int?}", Name="ProductIndex")]
public ActionResult Index(string brand, string category, int? page, string subcategory = "")

并给出/Nike/Shoes/Running 但没有/Nike/Shoes 但/Products?brand=Nike&category=Shoes

当我添加

[HttpGet]
[Route("{brand}/{category}/{page:int?}")]
public ActionResult Index(string brand, string category, int? page)

/Nike/Shoes/有效,但我也有/Nike/Shoes/?subcategory=Running

和我的详细方法:

[HttpGet]
[Route("{brand}/{category}/{subcategory}/{productid:int:min(9000)}", Name="ProductDetails")]
public ActionResult Details(int productid)

给出:

The current request is ambiguous between the following action methods: System.Web.Mvc.ActionResult Index(System.String, System.String, System.Nullable`1[System.Int32], System.String) on type shopmvc.Controllers.ProductsController System.Web.Mvc.ActionResult Index(shopmvc.ViewModels.ProductsViewModel) on type shopmvc.Controllers.ProductsController System.Web.Mvc.ActionResult Details(Int32) on type shopmvc.Controllers.ProductsController

所以我的产品链接和类别/子类别路由有问题。或者我尝试达到它的方式:

<a href="@Url.RouteUrl("ProductDetails", new { brand = item.Brand, category = item.Category, subcategory = item.SubCategory, productid = item.ID })">test</a>
<a href="@Url.Action("Details", "Products", new { brand = item.Brand, category = item.Category, subcategory = item.SubCategory, productid = item.ID })">
<a href="@Url.Action("Index", "Products", new { brand = c.Brand, category = c.Category, subcategory = c.SubCategory })">@c.DisplayName</a>

最佳答案

您是否尝试过对 Global.asax 中的路由进行排序,从最具体到最通用?您的应用程序不知道检查路由的顺序,因此类似 brand/category/subcategory/nnnnn 的内容可能是页面 nnnnn 或产品 nnnnn。

您需要先检查这条路线:

[HttpGet]
[Route("{brand}/{category}/{subcategory}/{productid:int:min(9000)}", Name="ProductDetails")]
public ActionResult Details(int productid)

然后这个:

[HttpGet]
[Route("{brand}/{category}/{subcategory}/{page:int?}", Name="ProductIndex")]
public ActionResult Index(string brand, string category, int? page, string subcategory = "")

或者,您可以修改路由,使页面路由如下所示:

`brand/category/subcategory/p-n`

例如/Nike/Shoes/Running/p-2

编辑:如果你这样做会发生什么?任何小于 9000 的数字都会被解释为页码,尽管这可能会让用户感到困惑!

[HttpGet]
[Route("{brand}/{category}/{subcategory}/{page:int?:max:8999}", Name="ProductIndex")]
public ActionResult Index(string brand, string category, int? page, string subcategory = "")

关于asp.net-mvc - MVC 路由可选字符串参数和难看的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30347462/

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