Skip to main content
 首页 » 编程设计

c#之如何避免在 RESTful Web API 2 中执行不同的相同操作

2024年05月10日44zfyouxi

我在设计 RESTful Web API 的过程中遇到了以下问题:我需要一个 Controller 来检索层次结构的集合(称为部分)以及检索单个部分(单个部分) ).如果我需要一个集合,我必须引用根部分的 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) 
  { 
     ... 
  } 

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

请您参考如下方法:

如果您想遵循标准的 REST 模式,您应该引入一个略有不同的 API:

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

通常您应该使用单一资源并仅为特定资源提供标识符。你不能有相同的 URL,即使使用不同的 Controller 也是如此。