【问题标题】:ASP.net Web API attribute routing with int and string带有 int 和 string 的 ASP.net Web API 属性路由
【发布时间】:2019-10-21 20:25:45
【问题描述】:

这应该很快。 我有两条路线:

[HttpGet]
[Route("{id}")]
[ResponseType(typeof(Catalogue))]
public IHttpActionResult Get(string id) => Ok(_catalogueService.Get(id));

[HttpGet]
[Route("{numberOfResults:int}")]
[ResponseType(typeof(IEnumerable<Catalogue>))]
public IHttpActionResult List(bool active, int numberOfResults) => Ok(_catalogueService.List(active, numberOfResults));

当我使用邮递员尝试列出我的目录时,我传递了类似这样的内容

/catalogues/10

我希望它在我的控制器中使用List 方法。同样,如果我想获取目录,我会传递如下内容:

/catalogues/AB100

我的路线可以正常工作,但我最近对List 方法进行了更改(我添加了活动布尔),现在我的路线无法正常工作。 我上面给出的两个示例都被错误的Get 方法捕获。

有没有办法解决这个问题?

【问题讨论】:

  • 这似乎是一个等待发生的问题,我强烈建议不要根据值是字符串还是整数来使用相同的路由。
  • 也许吧,但我不明白的是,我们在整个 API 中都使用了这个,只有这个有问题。
  • 仅仅因为你可以做某事并不意味着你应该这样做。现在可能不适用,但假设目录 ID 是 12345,您希望您的应用程序现在做什么?为未来这样的变化而构建,您将处于更安全的位置。
  • @r3plica 为active 添加一个默认值并将其放在numberOfResults 参数之后作为可选参数。由于额外的 required 参数,默认情况下它将不再匹配路由,因为即使不在路由模板中,它也会期望 active 成为 URL 的一部分。

标签: c# asp.net asp.net-web-api2 asp.net-web-api-routing


【解决方案1】:

active添加一个默认值并将其放在numberOfResults参数之后作为可选参数。

[HttpGet]
[Route("{numberOfResults:int}")]
[ResponseType(typeof(IEnumerable<Catalogue>))]
public IHttpActionResult List(int numberOfResults, bool active = true) => //assuming active default
    Ok(_catalogueService.List(active, numberOfResults));

由于额外的必需 active 参数,默认情况下它将不再匹配原始重载路由,因为它期望 active 成为 URL 的一部分,即使不在路线模板。

喜欢

/catalogues/10?active=true

通过使该参数成为可选参数,这意味着它现在可以像以前一样将预期的行为与从 URL 中省略时提供给操作的 active 值匹配

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多