我正在我的webapi 2项目中使用swashbuckle构建Swagger Docs。
我有以下方法的定义:
[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个好吗?这是令人困惑的,因为这不是有效的回应。
感谢您的建议。
您可以通过使用SwaggerResponseRemoveDefaults
属性来删除默认响应(200 OK)。
as vampiire 在他们的评论中指出, SwaggerResponseRemoveDefaults
不再在swashbuckle中。现在实现这一目标的方法是同时包括 <response>
xml-doc 和 [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响应。它取自Microsoft在Swashbuckle 5.5.0和ASP.NET Core 3.1
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");
}
}
}
}