C# ASP.NET核心:如何将路由参数与查询连接
我有一个带有连接操作的路由,它检索blog post drom数据库并显示它C# ASP.NET核心:如何将路由参数与查询连接,c#,asp.net-core,routing,C#,Asp.net Core,Routing,我有一个带有连接操作的路由,它检索blog post drom数据库并显示它 routes.MapRoute( 名称:“GetPostToShow”, 模板:“posts/{postId:int}”, 默认值:新建{controller=“Home”,action=“GetPostToShow”}, 约束:new{httpMethod=new-httpmethodoloteconstraint(新字符串[]{“GET”}); 这将导致url https://localhost:44300/po
routes.MapRoute(
名称:“GetPostToShow”,
模板:“posts/{postId:int}”,
默认值:新建{controller=“Home”,action=“GetPostToShow”},
约束:new{httpMethod=new-httpmethodoloteconstraint(新字符串[]{“GET”});
这将导致url
https://localhost:44300/posts/2002
但我希望它看起来像这样
https://localhost:44300/posts?postId=2002
那么我如何实现它呢??postId=2002是一个GET变量,可以作为controller方法中的参数获取 因此,您可以简化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)
当然,在我看来,使用decorator路由更好。然后,您将删除MapRoute调用,并将以下装饰器添加到该方法中:
[HttpGet("posts")]
public IActionResult GetPostToShow(int postId)
?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)
当然,在我看来,使用decorator路由更好。然后,您将删除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=yourspostsidhere})
您的路线如下所示
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=yourspostsidhere})
谢谢你这么做,但这只是另一个问题的序言。不幸的是,StackOverflow可以在90分钟内发布一个问题。所以,请继续关注。谢谢你的回答,但这只是另一个问题的序言。不幸的是,StackOverflow可以在90分钟内发布一个问题。所以请继续关注。