簡體   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