0

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?

2 Answers 2

2

?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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that works, but it was just preambula for another question. Unfortunately StackOverflow gives ability to post one question in 90 minutes. So stay tuned.
0

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})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.