Swashbuckle自动向生成的Swagger文件添加200 OK响应

时间:2016-06-14 13:22:28

标签: c# swagger swashbuckle

我正在WebApi 2项目中使用Swashbuckle构建swagger文档。

我有以下方法定义:

[HttpPost]
[ResponseType(typeof(Reservation))]
[Route("reservations")]
[SwaggerResponse(HttpStatusCode.Created, Type = typeof(Reservation))]
[SwaggerResponse(HttpStatusCode.BadRequest) ]
[SwaggerResponse(HttpStatusCode.Conflict)]
[SwaggerResponse(HttpStatusCode.NotFound)]
[SwaggerResponse(HttpStatusCode.InternalServerError)]        
public async Task<HttpResponseMessage> ReserveTickets([FromBody] ReserveTicketsRequest reserveTicketRequest)
{
    // ...
    return Request.CreateResponse(HttpStatusCode.Created, response);
}

但是生成的Swagger文件也包含HTTP 200 OK,尽管它没有在任何地方指定。

/reservations: 
  post: 
    tags: 
      - "Booking"
    operationId: "Booking_ReserveTickets"
    consumes: 
      - "application/json"
      - "text/json"
    produces: 
      - "application/json"
      - "text/json"
    parameters: 
      - 
        name: "reserveTicketRequest"
        in: "body"
        required: true
        schema: 
          $ref: "#/definitions/ReserveTicketsRequest"
    responses: 
      200: 
        description: "OK"
        schema: 
          $ref: "#/definitions/Reservation"
      201: 
        description: "Created"
        schema: 
          $ref: "#/definitions/Reservation"
      400: 
        description: "BadRequest"
      404: 
        description: "NotFound"
      409: 
        description: "Conflict"
      500: 
        description: "InternalServerError"
    deprecated: false

有没有办法摆脱200 OK?这令人困惑,因为它不是一个有效的回应。

感谢您的建议。

3 个答案:

答案 0 :(得分:11)

您可以通过使用$amount = 10000 $percentage = 1.1 $times = 1 属性修饰方法来删除默认响应(200 OK)。

答案 1 :(得分:1)

vampiire 在他们的评论中指出,SwaggerResponseRemoveDefaults不再在Swashbuckle中。现在实现此目的的方法是同时为该方法包括<response> XML文档和 [ProducesResponseType()]属性:

/// ...
/// <response code="201">Returns the newly reserved tickets</response>
/// <response code="400">If the input parameters are invalid</response>
/// ...
[HttpPost]
[Route("reservations")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
...
public async Task<HttpResponseMessage> ReserveTickets([FromBody] ReserveTicketsRequest reserveTicketRequest)
{
    ...
}

这将删除默认的200响应。它取自Swashbuckle 5.5.0和ASP.NET Core 3.1上的Microsoft's Swashbuckle documentation

答案 2 :(得分:0)

        services.AddSwaggerGen(c =>
        {
            c.OperationFilter<Api.Swagger.RemoveDefaultResponse>();
        });

   public class RemoveDefaultResponse : IOperationFilter
   {

    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation.Responses.TryGetValue("200", out var response)) {
            if (response.Description == "Success") {
                operation.Responses.Remove("200");
            }
        }
    }

   }