【问题标题】:Dot.NET Core Routing and Controller Processing discrepancyDot.NET Core 路由和控制器处理差异
【发布时间】:2021-05-24 15:02:16
【问题描述】:

我正在尝试使用 asp-route- 来构建用于查询数据库的查询字符串。 我对 asp-route- 的工作原理感到困惑,因为我不知道如何专门使用我在我的 cshtml 页面中创建的路由。例如:

如果我使用老式的 href 参数方法,那么我可以在我的控制器中使用指定的 Query 来获取参数并查询我的数据库,如下所示:

如果我使用这个href:

<a href="/Report/Client/?ID=@ulsin.ID">@ulsin.custName</a>

然后,在控制器中,我可以使用这个:

HttpContext.Request.Query["ID"]

上述方法有效,我可以使用该参数。但是,如果我使用 htmlHelper 的方式,比如:

<a asp-controller="Report" asp-action="Client" asp-route-id="@ulsin.ID">@ulsin.custName</a>

如何从控制器获取该 ID?在这种情况下,href 方法似乎不起作用。

【问题讨论】:

    标签: asp.net-core url-routing


    【解决方案1】:

    根据Anchor Tag Helper documentation,如果在路由中找不到请求的路由参数(在您的情况下为id),则将其添加为查询参数。因此,将生成以下最终链接:/Report/Client?id=something。注意查询参数是小写的。

    当您现在尝试在控制器中以HttpContext.Request.Query["ID"] 访问它时,由于HttpContext.Request.Query 是一个集合,索引它会区分大小写,因此“ID”不会为您获取查询参数“id”。无需尝试手动解决此问题,您可以使用称为 model binding 的框架功能,它允许您自动且不区分大小写地获取查询参数的值。

    这是一个示例控制器操作,它使用模型绑定来获取查询参数id 的值:

    // When you add the id parameter, the framework's model binding feature will automatically populate it with the value of the query parameter 'id'.
    // You can then use this parameter inside the method.
    public IActionResult Client(int id)
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多