繁体   English   中英

多个路由相同的动作 .NET Core 3.1

[英]Multiple routes same action .NET Core 3.1

我正在尝试在 .cshtml 中创建一个锚元素,选择多个之间的特定路由。

控制器:

[Route(""), Route("Products")]
public class ProductsController : Controller 
{
    [HttpGet, Route("Search"), Route("Category/{category}")]
    public IActionResult SearchAction(string query, string category)
    {
        ...
    }
}

.cshtml:

//This two options return "Search?category=A", but I don't want the first route
<a href="@Url.Action("SearchAction", "Products", new { category = "A" })">Link</a>
<a asp-controller="Products" asp-action="SearchAction" asp-route-category="A">Link</a>

//This return null, I want to define which route will be chosen
<a href="@Url.RouteUrl("Search", new { category = "A" })">Link</a>
<a href="@Url.RouteUrl("Products/Search", new { category = "A" })">Link</a>
<a asp-route="Search" asp-route-category="A">Link</a>
<a asp-route="Products/Search" asp-route-category="A">Link</a>
<a href="@Url.RouteUrl("Category", new { category = "A" })">Link</a>
<a href="@Url.RouteUrl("Products/Category", new { category = "A" })">Link</a>
<a asp-route="Category" asp-route-category="A">Link</a>
<a asp-route="Products/Category" asp-route-category="A">Link</a>
<a asp-route="Category/A">Link</a>
<a asp-route="Products/Category/A">Link</a>

谢恩科西

您需要为路线命名。

我必须命名路由,但这导致我遇到另一个问题,路由应该有一个唯一的模板来命名。 所以我从控制器中删除了路由,只在操作中指定。

public class ProductsController : Controller 
{
    [HttpGet, Route("Products/Search", Name = "Products/Search"), Route("Category/{category}", Name = "Products/Category")]
    public IActionResult SearchAction(string query, string category)
    {
        ...
    }
}

我能够像这样使用:

<a asp-route="Products/Category" asp-route-category="A">Link</a>
<a href="@Url.RouteUrl("Products/Category", new { category = "A" })">Link</a>
<a asp-route="Products/Search" asp-route-category="A">Link</a>
<a href="@Url.RouteUrl("Products/Search", new { category = "A" })">Link</a>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM