Web api - how to route using slugs?

2020-04-14 08:51发布

问题:

I would like to be able to parse links like this question is:

http://stackoverflow.com/questions/31223512/web-api-how-to-route-using-slugs

So route on the server simply ignoring the last part of the URL. As an example using this very question, how could I implement the routing correctly if somebody enters such an URL, it redirects me to:

http://stackoverflow.com/questions/31223512

回答1:

Referencing: Handling a Variable Number of Segments in a URL Pattern

Sometimes you have to handle URL requests that contain a variable number of URL segments. When you define a route, you can specify that if a URL has more segments than there are in the pattern, the extra segments are considered to be part of the last segment. To handle additional segments in this manner you mark the last parameter with an asterisk (*). This is referred to as a catch-all parameter. A route with a catch-all parameter will also match URLs that do not contain any values for the last parameter.

A convention-based route could be mapped as...

config.Routes.MapHttpRoute(
    name: "QuestionsRoute",
    routeTemplate: "questions/{id}/{*slug}",
    defaults: new { controller = "Questions", action = "GetQuestion", slug = RouteParameter.Optional }
);

or, with attribute routing a route could look like...

[Route("questions/{id:int}/{*slug?}")]

which could both match an example controller action...

public IActionResult GetQuestion(int id, string slug = null) {...}

the example URL...

"questions/31223512/web-api-how-to-route-using-slugs"

would then have the parameters matched as follows...

  • id = 31223512
  • slug = "web-api-how-to-route-using-slugs"

And because the slug is optional, the above URL will still be matched to

"questions/31223512"

This should meet your requirements.