【问题标题】:Route url is including ?=路由 url 包括 ?=
【发布时间】:2020-06-10 11:50:43
【问题描述】:

我在我的页面中使用以下 Razor:

<a asp-action="Logs" asp-route-channel="@channel.Name">
     <button class="btn btn-success btn-circle"><i class="fa fa-eye"></i></button>
</a>

channel 是字符串,而不是整数,这就是我不使用id 的原因。

这就是我的路由方式:

endpoints.MapControllerRoute("logs", "Dashboard/Logs/{channel}");

在我的控制器中,我只是为了测试目的而这样做:

public IActionResult Logs(string channel)
{
    return Content(channel);
}

但是,当链接生成时,我得到这样的东西:

<a href="/Dashboard/Logs?channel=mychannel">

而不是预期的:

<a href="/Dashboard/Logs/mychannel">

编辑

这是我尝试过的:

[HttpGet("{channel}")]
public IActionResult Logs(string channel)
{
    return Content(channel);
}

导致https://localhost:44351/mychannel

我也试过了:

[HttpGet("Dashboard/Logs/{channel}")]
public IActionResult Logs(string channel)
{
    return Content(channel);
}

哪个按预期工作,但为什么我必须像这样包含整个路径?

【问题讨论】:

  • 为什么不使用属性路由?
  • 那我得写[HttpGet("Dashboard/Logs/{channel}")],这看起来有点傻,因为它应该知道我的Controller和Action是什么。
  • 您正在映射到默认路由,该路由很可能具有 id 。显示所有映射并包括控制器定义。

标签: asp.net asp.net-mvc asp.net-core routes


【解决方案1】:

您正在映射到基于默认约定的路由,该路由很可能将{id} 作为路由参数。因为它映射到默认值并且您包含了{channel},所以它会将该参数添加为查询字符串而不是 URL 的一部分。

您需要为该操作添加自定义路由才能生成所需的 URL。

endpoints.MapControllerRoute(
    name: "Logs",
    pattern: "Dashboard/Logs/{channel}",
    defaults: new { controller = "Dashboard", action = "Logs" });

endpoints.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" });

并且需要包含必要的路由值,以便映射到预期的路由

<a asp-controller="Dashboard" asp-action="Logs" asp-route-channel="@channel.Name">
     <button class="btn btn-success btn-circle"><i class="fa fa-eye"></i></button>
</a>

【讨论】:

    猜你喜欢
    • 2020-08-28
    • 1970-01-01
    • 2013-10-07
    • 2018-01-13
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多