Web api - 如何使用 slug 进行路由?
Web api - how to route using slugs?
我希望能够像这个问题一样解析链接:
因此服务器上的路由只是忽略 URL 的最后一部分。作为使用这个问题的示例,如果有人输入这样的 URL,我如何才能正确实现路由,它会将我重定向到:
引用: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?}")]
两者都可以匹配示例控制器操作...
public IActionResult GetQuestion(int id, string slug = null) {...}
示例URL...
"questions/31223512/web-api-how-to-route-using-slugs"
那么参数匹配如下...
id = 31223512
slug = "web-api-how-to-route-using-slugs"
并且因为 slug
是可选的,上面的 URL 仍然会匹配到
"questions/31223512"
这应该符合您的要求。
我希望能够像这个问题一样解析链接:
因此服务器上的路由只是忽略 URL 的最后一部分。作为使用这个问题的示例,如果有人输入这样的 URL,我如何才能正确实现路由,它会将我重定向到:
引用: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?}")]
两者都可以匹配示例控制器操作...
public IActionResult GetQuestion(int id, string slug = null) {...}
示例URL...
"questions/31223512/web-api-how-to-route-using-slugs"
那么参数匹配如下...
id = 31223512
slug = "web-api-how-to-route-using-slugs"
并且因为 slug
是可选的,上面的 URL 仍然会匹配到
"questions/31223512"
这应该符合您的要求。