Web api - how to route using slugs?

本秂侑毒 提交于 2019-12-02 01:41:47

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!