c# - Web api - 如何使用 slugs 进行路由?

标签 c# asp.net-web-api routes

我希望能够像这个问题一样解析链接:

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/

相关文章:

c# - 用于过滤的 Web API 动态参数

c# - 当 "externalizing"某些配置设置进入外部文件时行为不同

routes -/favicon.ico 被附加到 Rails 4 路由

c# - 从 .NET 连接到 LDAP 服务器

C# 连接到 Oracle DB 日期时间格式

c# - 使用 Json 比较 C# 对象

asp.net-mvc - 如何将用户重定向到 ASP.NET MVC 中的自定义 404 页面而不是引发异常?

c# - 计算不同类型内存的算法

c# - 仅当使用 unity DI 回收应用程序池时,webapi 调用才会失败

Ajax 调用 Laravel 路由