Reputation: 141
I have route with connected action which retrieves blog post drom database and displays it.
routes.MapRoute(
name: "GetPostToShow",
template: "posts/{postId:int}",
defaults: new { controller = "Home", action = "GetPostToShow" },
constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });
Which results in url
https://localhost:44300/posts/2002
But I want it to look like this
https://localhost:44300/posts?postId=2002
So how I can implement it?
Upvotes: 0
Views: 225
Reputation: 721
?postId=2002 is a GET variable and can be gotten as an argument in the controller method.
So you wouild simplify your MapRoute:
routes.MapRoute(
name: "GetPostToShow",
template: "posts",
defaults: new { controller = "Home", action = "GetPostToShow" },
constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });
And in the Controller have the Method:
public IActionResult GetPostToShow(int postId)
Of course even nicer is to use the decorator routing in my opinion. Then you would remove the MapRoute call and instead add the following decorator to the method:
[HttpGet("posts")]
public IActionResult GetPostToShow(int postId)
Upvotes: 2
Reputation: 461
Your routes look like below
routes.MapRoute(
name: "GetPostToShow",
template: "posts/{postId(0)}",
defaults: new { controller = "Home", action = "GetPostToShow" },
constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });
Your GetPostToShow method in controller side look like below.
public virtual IActionResult GetPostToShow (int postId)
{
// your code and return view
}
Or into CSHTML page you want to use like below code.
@Url.RouteUrl("posts", new {postId= yourpostsIdhere})
Upvotes: 0