Swashbuckle:具有相同状态代码但不同 description/model 的多个 [SwaggerResponse]

Swashbuckle: Multiple [SwaggerResponse] with the same status code but different description/model

我正在编写一个演示购物车 API 我遇到过这样一种情况,我可以 return NotFound 出于多种原因(找不到购物车商品或购物车本身是找不到的)。我想 return 对这两种情况进行 Swagger 描述。我已经试过了,但没有用。

    [SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(CartNotFoundResponse), Description = "Cart not found (code=1)")]
    [SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(ItemNotFoundResponse), Description = "Item not found (code=104)")]
    [SwaggerResponse(HttpStatusCode.NoContent)]
    public async Task<IHttpActionResult> DeleteItemWithSKUAsync(Guid cartId, string sku)
    {
    }

有什么建议吗?

不幸的是,当前的实现是不可能的: https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Swagger/SwaggerDocument.cs#L29

如您所见,响应是一个字典,键是 StatusCode。

我的建议:使用更通用的 class 可以涵盖你们两个案例(CartNotFound 和 ItemNotFound)

考虑不关心:

  1. 找不到购物车;
  2. 未找到该项目或已被删除。

无论您是否真的删除了某些内容,都只需使用 NoContent 进行响应。如果它不存在,它就不存在,这正是你想要发生的。

为什么我建议这样做? 因为它使您的 API 不那么复杂,并且让您不必考虑购物车或购物车商品根本不存在的情况。

但是,如果我尝试删除不存在的内容时我的数据库抛出错误怎么办? 抓住它并假装你删除了它。让您的 API 以 NoContent 响应,因为确实没有内容。