我希望能够像这个问题一样解析链接:
http://stackoverflow.com/questions/31223512/web-api-how-to-route-using-slugs
因此服务器上的路由只是忽略 URL 的最后部分。作为使用这个问题的示例,如果有人输入这样的 URL,我将如何正确实现路由,它将我重定向到:
http://stackoverflow.com/questions/31223512
最佳答案
引用: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.
基于约定的路由可以映射为...
config.Routes.MapHttpRoute(
name: "QuestionsRoute",
routeTemplate: "questions/{id}/{*slug}",
defaults: new { controller = "Questions", action = "GetQuestion", slug = RouteParameter.Optional }
);
或者,使用属性路由,路由可能看起来像...
[Route("questions/{id:int}/{*slug?}")]
两者都可以匹配示例 Controller 操作...
public IActionResult GetQuestion(int id, string slug = null) {...}
示例网址...
"questions/31223512/web-api-how-to-route-using-slugs"
然后将按如下方式匹配参数...
id = 31223512
slug = "web-api-how-to-route-using-slugs"
而且因为 slug
是可选的,上面的 URL 仍然会匹配到
"questions/31223512"
这应该符合您的要求。
关于c# - Web api - 如何使用 slugs 进行路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31223512/