Reputation: 311
I am building swagger docs using Swashbuckle in my WebApi 2 project.
I have the following definition of the method:
[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);
}
However the generated Swagger file contains HTTP 200 OK as well, although it's not specified anywhere.
/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
Is there a way to get rid of that 200 OK? It's confusing as it's not a valid response.
Thanks for suggestions.
Upvotes: 14
Views: 6444
Reputation: 9674
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");
}
}
}
}
Upvotes: 1
Reputation: 358
As vampiire points out in their comment, SwaggerResponseRemoveDefaults
is no longer in Swashbuckle. The way to achieve this now is to include both a <response>
XML-doc and a [ProducesResponseType()]
attribute to the method:
/// ...
/// <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)
{
...
}
This will remove the default 200 response. It's taken from Microsoft's Swashbuckle documentation on Swashbuckle 5.5.0 and ASP.NET Core 3.1
Upvotes: 3
Reputation: 5904
You can remove the default response (200 OK) by decorating the method with the SwaggerResponseRemoveDefaults
attribute.
Upvotes: 13