【问题标题】:Web api Restful : Get resource by foreign keyWeb api Restful : 通过外键获取资源
【发布时间】:2021-02-12 18:32:02
【问题描述】:

我的问题是关于在以下情况的 .NET 核心 Web API 中命名路由的“正确方法”:

  • 银行帐户始终与企业相关。
  • 一个企业可以有多个银行账户
  • 一份合同总是有一个银行账户

所以我有这样的资源:

/api/enterprise/1 // get enterprise 1
/api/contract/1 // get contract 1
/api/bank-account/1 //get bankaccount  1

我的问题是,获得企业银行账户的最佳方式是什么?

第一个想法:

使用查询字符串作为“搜索词”

api/bank-account?EnterpriseId=1

第二个想法

使用子资源

api/enterprise/1/bank-account

但如果我这样做,我有多个不同级别的“银行账户”,我不知道这是否是一个好方法?

api/enterprise/1/bank-account //bank-account level2
api/bank-account //bank-account level1

我认为第二个想法是一个好方法,但我不确定是否可以在不同级别的 api 上操作相同的“模型”。

谢谢。 祝你有美好的一天

【问题讨论】:

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


    【解决方案1】:

    看看微软路由Web API的例子:Routing in ASP.NET Web Api

    我更喜欢第二个想法。稍微完善一下

    例如:

    api/enterprise      //return List of enterprise objects if needed
    api/enterprise/1    //return specific enterprise with id 1
    api/enterprise/1/bank-account    //return list of bank accounts for enterprise with id 1
    api/enterprise/1/bank-account/1  //return specific bank account with id 1
    

    如果您想在特定企业的上下文中获取银行帐户

    但如果你只想通过 id 获取银行账户,最好这样做

    api/bank-account/1
    

    在这个用例中,如果不添加带有企业 ID 的查询字符串,您将无法真正获取特定企业的银行账户,因为

    api/bank-account  //this should return list of bank accounts ALL BANK ACCOUNTS
    

    这是一个多级控制器示例:

    [Route("Inventories/{inventoryId}/[controller]")]
    [ApiController]
    public class InventoryEntriesController : ControllerBase
    {
        ...
        
        // GET: Inventories/{inventoryId}/InventoryEntries
        [Authorize]
        [HttpGet]
        public async Task<ActionResult<IEnumerable<InventoryEntryDto>>> GetInventoryEntries(int inventoryId)
        {
            ...
        }
        
        // GET: Inventories/{inventoryId}/InventoryEntries/{id}
        [Authorize]
        [HttpGet("{id}")]
        public async Task<ActionResult<InventoryEntryDto>> GetInventoryEntry(int id)
        {
            ...
        }
    
        // POST: Inventories/{inventoryId}/InventoryEntries
        [Authorize]
        [HttpPost]
        public async Task<ActionResult<InventoryEntryDto>> AddInventoryEntry(InventoryEntryDto inventoryEntryDto)
        {
            ...
        }
    
        // PUT: Inventories/{inventoryId}/InventoryEntries/{id}
        [Authorize]
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateInventoryEntry(int id, InventoryEntryDto inventoryEntryDto)
        {
            ...
        }
    
        // DELETE: Inventories/{inventoryId}/InventoryEntries/{id}
        [Authorize]
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteInventoryEntry(int id)
        {
            ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-09
      • 2012-06-21
      • 2021-10-23
      • 1970-01-01
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多