路由参数不同的多个 HttpGet 不能支持不同的 SwaggerResponse。



我使用Swashbuckle.AspNetCore.Annotations来增强生成的文档。我有一个简单的c#控制器,它具有标准的Get, Post, Delete端点。当我添加了一个带有路由参数的额外HttpGet时,问题就出现了,这个参数应该足以区分并且仍然生成swagger文档。

一切似乎都很好,直到我尝试将SwaggerResponse修改为一个端点/entities返回实体页面,其中/entities/{id}端点返回单个实体结果。

我修改了属性注释:

[HttpGet]
[SwaggerOperation(
Summary = "summary here",
Description = "description",
OperationId = "GetPage",
Tags = new[] { "Entity" })]
[Produces("application/json")]
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(PaginationResult<EntityTransferObject>))]
[SwaggerResponse(StatusCodes.Status401Unauthorized)]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
public async Task<ActionResult> GetAsync(
[FromQuery] [SwaggerParameter("The entity type", Required = true)] string entityType,
[FromQuery] [SwaggerParameter("The page number to return", Required = true)]
int page,
[FromHeader(Name = "Authorization")] [SwaggerIgnore]
string token)
{

}

[HttpGet("{id:guid}")]
[SwaggerOperation(
Summary = "summary here",
Description = "description",    
OperationId = "GetEntity",
Tags = new[] { "Entity" })]
[Produces("application/json")]
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ExecuteQueryResult<EntityTransferObject>))]
[SwaggerResponse(StatusCodes.Status401Unauthorized)]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
public async Task<ActionResult> GetAsync(
[FromRoute] [SwaggerParameter("The entity id", Required = true)] Guid id,
[FromHeader(Name = "Authorization")] [SwaggerIgnore]
string token)
{
}

如果我然后生成swagger文档,我就会遇到一个错误,它无法加载API定义。如果我将swagger响应类型更改为与2/GET方法相同,它将工作。如果我只将属性添加到一个端点,它也会工作。

如果端点不同,它们应该支持不同的状态码响应类型?我试过使用。net CoreProducesResponseType,结果出现了同样的问题。我也试过调整返回类型以更具体,例如Task<ActionResult<PaginationResult<EntityTransferObject>>>,这也有同样的问题。

是否有其他方法可以增强两个端点的返回类型的文档输出?

似乎swagger感到不安,因为两个端点返回的类型包含相同的传输对象。

PaginationResult,它有一个TransferObject列表,QueryResult只有1个TransferObject。虽然是不同的类型,但TransferObject导致"不能对类型Y使用schemaId",因为它已经用于类型z了。

我通过在swagger配置 中添加以下行来修复这个问题
services.AddSwaggerGen(
c =>
{
// Removed earlier config for simplicity
c.CustomSchemaIds(type => type.ToString());
});

最新更新