【问题标题】:How to avoid identical actions that do different things in RESTful Web API 2?如何避免在 RESTful Web API 2 中执行不同操作的相同操作?
【发布时间】:2016-03-19 16:00:09
【问题描述】:

我正在设计一个 RESTful Web API 并且遇到了以下问题:我需要一个控制器来检索层次结构的集合(称为部分)以及检索单个部分(单个部分)。如果我需要一个集合,我必须参考根部分的 ID,它为我提供了整个结构的子树。所以我继续定义了一个像这样的 SectionsController:

public class SectionsController : ApiController
{
  // GET api/sections/5
  // Gets a subtree.
  public IEnumerable<Section> Get(int rootId)
  {
     ...
  }

  // GET api/sections/5
  // Gets a single section.
  public Section Get(int sectionId)
  {
     ...
  }

这显然不起作用,因为签名是相同的。推荐的解决方法是什么?

【问题讨论】:

  • 把它们放在不同的控制器中,或者给它们更具体的名字。如GetSectionsWithRoot
  • 我想过把它们放在不同的控制器中。至于第二个建议,那不会违反 REST 吗?我想以 api/sections (GET) 和 api/sections/5 (GET) 的形式结束 URI,所以我猜 api/subsections/5 会很好。不确定 GetSectionsWithRoot 会导致什么结果。
  • 我想它确实违反了 REST,但并非所有 API 都严格遵守 REST 准则 :)。无论如何,你可以写/api/hierarchy/5。编辑;或者是的,/subsections/ 也有效

标签: c# rest asp.net-web-api


【解决方案1】:

如果您想遵循标准 REST 模式,您应该引入稍微不同的 API:

public class SectionsController : ApiController
{
  // GET api/section
  public IEnumerable<Section> GetAll()
  {
     ...
  }

  // GET api/section/5
  public Section Get(int sectionId)
  {
     ...
  }

通常您应该使用单一资源并仅为特定资源提供标识符。即使使用不同的控制器,您也不能拥有相同的 URL。

【讨论】:

    【解决方案2】:

    阅读this post on SO关于图像传输的内容并点击链接,我意识到这个问题有一个非常简单的解决方案,它尊重 REST,同时不需要额外的控制器。

    只需返回对象中为特定 ID 请求的子树 ID 的集合,即

    public class Section
    {
       public int Id { get; set; }
       public string Name { get; set; }
       public int[] DescendantIds { get; set; }
    }
    

    所以只需一次调用

    api/section/5
    

    我获得了 ID 为 5 的部分的所有详细信息以及以下部分的 ID。是的,这会涉及一些开销,因此您必须自己决定此解决方案是否适合您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2016-04-10
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 2021-11-05
      相关资源
      最近更新 更多