Web API-如何使用进行路由? [英] Web api - how to route using slugs?

查看:75
本文介绍了Web API-如何使用进行路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够解析这样的链接:

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

因此在服务器上进行路由只需忽略网址的最后一部分。作为使用这个问题的示例,如果有人输入这样的URL,如何正确实现路由,它将我重定向到:

So route on the server simply ignoring the last part of the URL. As an example using this very question, how could I implement the routing correctly if somebody enters such an URL, it redirects me to:

http://stackoverflow.com/questions/31223512


推荐答案

引用:在URL模式中处理可变数量的段


有时,您必须处理包含可变数量的
URL段的URL请求。定义路线时,如果URL的段数大于模式中的段数,则可以指定
,多余的
段被视为最后一个段的一部分。要以这种方式处理
个附加段,请在最后一个参数上标记一个
星号(*)。这称为全部参数。具有包罗万象参数的路由
还将匹配不包含
最后一个参数任何值的URL。

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) {...}

示例网址...

"questions/31223512/web-api-how-to-route-using-slugs"

然后将参数匹配如下。

would then have the parameters matched as follows...


  • id = 31223512

  • slug =网络API如何使用鼻塞进行路由

  • id = 31223512
  • slug = "web-api-how-to-route-using-slugs"

并且由于 slug 是可选的,因此上述URL仍将与

And because the slug is optional, the above URL will still be matched to

"questions/31223512"

这应该满足您的要求。

这篇关于Web API-如何使用进行路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆