Web api - how to route using slugs?

前端 未结 1 635
逝去的感伤
逝去的感伤 2021-01-20 17:52

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

相关标签:
1条回答
  • 2021-01-20 18:30

    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.

    0 讨论(0)
提交回复
热议问题