Dot.NET 核心路由和控制器处理差异

Dot.NET Core Routing and Controller Processing discrepancy

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

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

如果我使用这个 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 方法在这种情况下似乎不起作用。

根据Anchor Tag Helper documentation,如果在路由中找不到请求的路由参数(id),则将其添加为查询参数。因此,将生成以下最终link:/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)