ASP.NET 核心:如何将路由参数与查询连接起来

ASP.NET Core: How to connect route parameter with query

我有连接操作的路由,它检索博客 post drom 数据库并显示它。

routes.MapRoute(
    name: "GetPostToShow",
    template: "posts/{postId:int}",
    defaults: new { controller = "Home", action = "GetPostToShow" },
    constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });

这导致 url

https://localhost:44300/posts/2002

但我希望它看起来像这样

https://localhost:44300/posts?postId=2002

那么我该如何实施呢?

?postId=2002 是一个 GET 变量,可以作为控制器方法中的参数获取。

因此您将简化您的 MapRoute:

routes.MapRoute(
name: "GetPostToShow",
template: "posts",
defaults: new { controller = "Home", action = "GetPostToShow" },
constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });

控制器中有方法:

public IActionResult GetPostToShow(int postId)

当然,我认为使用装饰器路由更好。然后您将删除 MapRoute 调用,而是将以下装饰器添加到方法中:

[HttpGet("posts")]
public IActionResult GetPostToShow(int postId)

您的路线如下所示

routes.MapRoute(
name: "GetPostToShow",
template: "posts/{postId(0)}",
defaults: new { controller = "Home", action = "GetPostToShow" },
constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });

控制器端的 GetPostToShow 方法如下所示。

public virtual IActionResult GetPostToShow (int postId) 
{
    // your code and return view
}

或者像下面的代码一样进入你想使用的 CSHTML 页面。

@Url.RouteUrl("posts", new {postId= yourpostsIdhere})